What do you want to learn?
Skip to main content
by Jesse Liberty
Resume CourseBookmarkAdd to Channel
Table of contents
We stated earlier that it's important to use braces even if you're working on a single statement in your if statement. Let's take a look at why. We'll return to our application, open up ifStatement.js, copy that, and move that into script.js because that's the file that will be run when we run the program. Let's remove the braces, and you'll find that this application runs exactly as intended. If you're under 40, you'll get this Oh you're so young and then Thank you, and if you're 40 or over, you'll just get Thank you as we saw earlier. However, let's say we decide to add a second alert for those who are under 40. Now, a naive programmer would come along and say if under 40 run this alert and this second alert and then the Thank you, and if you're over 40 the if will fail and you'll just get the Thank you. Let's see what happens if you're over 40. We're going to put in the age 50 and run this, and 40 is a drag. Why is that coming up? Let's go back to the code. An if statement only controls one statement, so even though this is indented, what is actually happening is if you're under 40, this one statement will run, and then this is outside of the if statement. That's why we use braces. Braces will put both of these inside the if statement, and now this will run as intended because the braces are going to contain both of these alerts into what is effectively a single statement, what's called a block.
We've looked at the if statement, which tests the condition and executes its statements if the condition is true. There are times that we want to execute a different block if the condition is false. In that case, we can use the if and the else statement together. Let's look at an example. We return to the logic of our if statement, and it says if the age is under 40, and then we're going to say, Oh you're so young... But what if the age is not under 40? In that case, we can add an else statement and we can say whatever we think is appropriate in the else statement. For example, this trite message. Now, the logic is we gather the age from the user and if the age is less than 40, we give the message on line 5. Otherwise or else, we give the message on line 9. And then in either case, we give the Thank you message. Let's run this, put in the age 50, and this time we get the message associated with the else statement followed, of course, by the Thank you message. Sometimes we have more than one condition to check. For example, we might want to know if the user is exactly 40. In that case, we can add in else if statement. This puts a middle test in that tests to see if the age is exactly 40. And notice we end with an else for over 40. Also, notice that equals uses two equal signs. One equal sign is assignment. Two equal signs is equals. Some people pronounce this equal equals. Now, if we run the application and we put in 40, we get the expected message.
While and Do While
We've looked at the if, else statement and we also looked at the if, else, else, if statement. Let's switch over now and take a look at another powerful control flow statement, the while statement, and with it, its companion, the do while statement. We'll start by once again asking the user for his or her age. We can actually combine these two statements into one if we wish because notice what we're doing is we're getting back a string from the prompt and then we're casting that to a number and putting it into age. We can combine these two statements by taking this entire prompt and putting it inside as an argument to the number function. Now, the logic of this statement is set age equal to what you get when you call number on what you get when you call prompt and ask what is your age. Prompt will return a string, number will turn that into a number, and that will be assigned to the variable age. Let's print a happy birthday message for every year of the person's age. This program has a number of new features, in addition to combining the prompt and the number. Let's walk through it. We begin by declaring a string to be an empty string. Our variable is named string. That doesn't make it a string. We could have called it anything. We could have called it Jimmy. Then we have a while statement. Everything within the while statement, everything within that block, will execute as long as this condition is true, age is greater than 0. What we're doing within that block is we're concatenating the string. We're saying the string plus equal, that is add to the end of this string happy birthday. And then we have a new escape sequence. Remember we had slash double quote to escape the quote. Slash N makes a new line. We then take age and we subtract 1 from age and assign it back to age. Another way to write this is age -= 1. Just as we're using the plus equal for concatenation to itself, we can say to the age subtract 1 and set it back to age with minus equal. Remember that this while loop will iterate again and again while age counts down to 0, but when it hits 0 it'll stop and then we will print the string. Let's run the application. We're prompted for our age. Let's set an age of 6 and say OK. And the alert comes up, and sure enough we have six happy birthdays. The interesting thing about a while loop is it may never run. Notice I have here while age is greater than 0. If I run this program and I set the age to 0, the age is not greater than 0, the block will never run and there is no message to display. There are times that you want to make sure that your block runs at least once. In that case, you can use a do while loop. A do while loop works just like a while loop except that the while is at the end. What this says is do what's in this loop while the age is greater than 0, but the while is not evaluated until you go through the loop, and so this will always run at least once. And if we run our application and we put in an age of 0, we get one happy birthday. What happens if we put in an age of 6? We get the proper amount, six happy birthdays. So, a do while loop can be very convenient because you still get the same logic as the while loop, but you're guaranteed to run at least one time. However, the while loop is the more popular construct.
It is not uncommon with the if statement or the while statement to initialize a condition, run your loop, change the condition, test the condition, and if it's still true, run again. All of that can be combined in a single for loop statement. Let's look at an example. You can probably figure this program out without any help. On line 1, we once again prompt for the age. On line 3, we set a blank string. It's line 4 that's new. Here we initialize a variable, which we're calling the age to the age that we were given, we test the condition is the age greater than 0, and each time through the loop we decrement the age by one. The order in which this happens is initialization, test, run the loop, and then do the decrement or increment or whatever change you're going to put in that third argument to the for loop. This works very much like the while loop worked before, but it's tighter and cleaner, and to a degree easier to understand. Let's run this. We'll put in an age of 6, and sure enough, we get six happy birthday messages.
There are times for one reason or another that you will want to break out of a while loop or a for loop. For that, you will use the keyword break. In this new example, I once again ask for the age, but this time I've reversed the for loop. I've set the counter to begin at 1 to count up to the user's age, and as long as it's less than the age, to continue. However, I've also introduced a new if statement. This if statement says that if counter modulo 7. Modulo is a new operator. It uses the percent sign and it means is evenly divisible by 7. Counter modulo 7 is going to divide the number by 7 and give you the remainder just like fourth grade arithmetic. So, if you give it the number 9, it will divide by 7 and return the remainder, which is 2. In this case, we're testing for when there is no remainder, that is the number is evenly divisible by 7. The first time it hits a number that's evenly divisible by 7; it will execute the break statement and break out of the for loop. Before I run this, try to guess what we'll see in the alert. Let's run this and put in a high value of 45, click OK, and what we see are seven happy birthdays. The loop runs continuously until it hits that evenly divisible by 7, and the first value that is 7 itself, and so it breaks out of the for loop and prints the seven happy birthdays. Here's the for loop. It's going to iterate through that arguably 45 times because that's the age we gave it, but as soon as it hits this counter modulo 7, when the value is 1, the remainder is 1, when the value is 2, the remainder is 2, but when the value is 7, the remainder is 0. It breaks out of the loop and prints the seven strings.
We looked earlier at the if, else, else, if construction, and while that certainly works, when there are enough else if statements, it can become difficult to read, and programs that are difficult to read are difficult to maintain. We can solve that problem by using a switch statement. Let's take a look at how the switch statement works. Let's return to using Plunker, which is a nice fast way to see the effects. And one trick is if Plunker's effects are happening too fast, you can click on the stop button, and that will let you write out all of your code and then click run to see the effect. What we're going to do is declare a variable and name it animal, and I'm going to preset animal to dog. Now, you can imagine that I might get animal from a prompt or I might get animal from the internet through a web service, through any number of different ways of obtaining that information, but somehow, I got a value for animal, and I want to do something different depending on what value that is. So, I could say if animal equal cat, do this, else if animal equal dog, do that, else if animal equal horse, do some third thing, and so forth. A cleaner, I think, approach to this is to switch on the animal itself. And so we type the keyword switch, and then in parens we put the variable we're switching on, in this case animal, we put everything within braces, and within the braces we put case statements. So, case cat, which really means if the animal is a cat, then what I want you to do is whatever work you're going to have the code do. In this case, we'll simply call alert. After the work for cat, we put a break statement, and that signals that's the end of the cat case. We can then have a case for dog and put an alert statement and a break statement for dog. And we can continue to do that for the various animals that we want to test for. So, we can test for horse, and if we get a horse, we can put an alert statement for the horse. Finally, and it's good programming practice, we can end with a default statement, and default is what the code will go to if none of the cases match. It's always a good idea to have a default that does something useful when none of the expected cases are going to match. In this case, we will match. We'll match on dog. Let's run the program. And we can see that what has happened is we've switched on animal, the case dog has matched, and we get an alert, woof. We don't get any of the other alerts because none of the other cases matched.
This module focused on truth, truthiness, false, and falsiness. We noted that the only Boolean values are true and false. We looked at the and operator, which returns true if both operands are true, we looked at the or operator, which returns true if either operand is true, and we looked at the not operator, which reverses the truth of whatever you apply it to. We also looked at the difference between equality and exact equality. Falsy values are equal equal with false, but are not equal equal equal with false.
Functions can be created in the name or they can be created anonymously without a name and optionally assigned to a variable, which can act as the name of the function. We'll see this at work when we create and call functions. When we create and call functions, we're also going to optionally pass in parameters, and we'll see that if we pass in too many arguments, they'll be ignored, and too few arguments, and they'll be undefined. Let's take a look at what all that means in a practical way. Let's start by creating a function called add. As you can see, we have the keyword function, and that is followed by the name of the function, in this case add, and two parentheses, always in open and closed parentheses. Sometimes within the parentheses is what are called parameters. In this case, we have two parameters, x and y. We're going to use those parameters within the body of the function, and they act just as if they were variables declared within the function. So, we can do things with them. For example, we can say var z equals x + y, just as if x and y had been declared in the function. We can even return a value from a function, so we'll return z. Now, how do we use this function? Well, one very easy way is to simply call it. Say add 5 and 7. The problem with this is that we're calling the function and we're immediately throwing away the return value. Let's capture that in a variable, which we'll call sum, and now we can do whatever we want with sum, including calling alert. Another way to declare this function is anonymously, taking away the name, but assigning the function to a variable. This really has the same effect in that we can use that variable name to invoke the function, and this will continue to run as intended. There'll be other times that you'll use anonymous functions without assigning it to a variable and have it called through other means. Notice that we have declared two parameters. There is no requirement that we pass in two parameters. If, for example, we pass in only one argument to the add function even though it has declared two parameters, the y parameter will be considered undefined, and so it will take 5 and assign it to x and set y to undefined, and then z will be the sum of 5 and undefined, which is not a number. And so when we call add, we'll get not a number. It's also possible that we'll pass in too many parameters. In that case, the extra parameters are simply ignored, 5 and 6 are added, and 7 and 8 are ignored.
We've seen that functions can return a value. If the function returns without returning a value, then the value is considered to be undefined. Let's take a look at that and also take a look at an alternative to using alert boxes. Here we return to our simple add function, and notice that when we want to get the results we are again calling alert, and that's displaying the answer for us. As an alternative to this, we can go into the HTML. Remember that we have an HTML page that has the link to the script. Let's move the script to the bottom of the page and add a div. We'll give that div an ID of output. No contents in the div. And that's where we're going to put our output now. Let's go back to script.js, and instead of saying alert.sum, we can say output.innerHTML = sum. And what that's going to do is to write the sum to the inner HTML property of that div. Let's see how that works. We're going to go ahead and click Run, and sure enough that 11 shows up in the HTML. One of the advantages of this is that we can put in a second solution, add 3 and 4, and then here in the sum we can say +, a space, + sum2, and sure enough we get 11 and 7. And, in fact, we could put a comma space to make it clear we've separated those, and we get an instant response in Plunker showing us that it's refreshing the page and displaying our values. Now, let's go back to just displaying the results of sum. What happens if instead of returning z, we just return with no value? Well in that case, add 5 and 6 has no value, that gets assigned to sum, and when we display it, it displays as undefined. A function that returns without returning a value is said to return undefined.
Functions and Scope
Here's a somewhat contrived example that we can use to take a look at nested functions and their scoping rules. Now, our outer function defined on line 3 is hypotenuse. We have two inner nested functions. On line 8, we have squareSide1, and on line 13, we have squareSide2. On line 18, we return the square root of calling the nested function squareSide1 and adding a call to the nested function squareSide2. Now, as you know, this is the simple formula for a hypotenuse. What's interesting about this from a scoping perspective is that squareSide1 has access to the local variables defined in the outer function hypotenuse. If there were variables defined inside squareSide1, they would not be visible in the outer function hypotenuse. This is parallel to what we saw between functions and global scope. So, once again, we see a function creating scope, but having access to its outer scope. This is contrived because we're using variables with fixed value, but we can see that it worked, and, in fact, the sides are 3, 4, 5, which is a common right triangle. We can make this somewhat less contrived by making hypotenuse take the values as parameters and have just one inner nested function square, which takes any value and returns it square. Now, we have a useful function with a nested function. And, in fact, if we pass in 3 and 4, we get back that the hypotenuse is 5.
Closure is a fancy computer science term, but all it means is that the function is called in the scope in which it was declared, not in the scope in which it's invoked. Now, what does that mean? Well, there are a couple implications to that. Let's take a look at a function that displays the scope of a local variable. Here we create a function called testScope. Inside that, we create a local variable scope, which is going to hide the outer global variable scope, we set the local variable to local, and then we create an inner nested function called innerFunc, which returns scope, and it's going to return that local scope. So, we'll add a line that says return the result of calling inner function. That's going to return local scope, and let's prove that to ourself. And we will assign the results of calling testScope to a local variable called answer, and we will put that into the innerHTML of our output, and sure enough, what comes up is local. Now, let's change this a little bit. Instead of having the testScope method return a call to innerFunc, let's have it return innerFunc itself. So, we take the parentheses off. Now, it's returning a function. And you can see, in fact, it is returning a function. We can then call that function by calling testScope and getting back the inner function and calling that. So, let's make a couple changes here. Now, what we've done is we've assigned a variable to what we get back from testScope, which is a function, and we've called that function assigning the result to answer. And, once again, we get local, and that's interesting. That's closure because we are calling innerFunc from the outer scope, and yet it is returning the scope from the time at which it was created, not at the time at which it's run. By the way, we can shorten this considerably. What this says is call testScope, we get back a function, and the second set of parentheses calls that function. So, it does just what the previous example did, only a little bit terser. So, one result of closure is that we are seeing the inner scope because the function is being called with the scoping at which it was declared. There is another side effect of closure. Here's another function. This one's somewhat contrived. We have a variable x, which is declared at global scope, a variable y that's declared within the function, and then we return x + y. Because this function forms a closure over x, that x is guaranteed to be available and in scope anytime this function is run. And so if x were to otherwise go out of scope because of callbacks or other reasons, it would be held in scope as long as some function might call it. And, of course, we can get an answer to this. And not surprising, the addition works as expected. We'll be returning to closure from time-to-time, but the key thing to remember is that the way closure works is that a function is going to scope its variables at the time it's declared, not at the time it's run.
Recursion is one of the more beautiful, if sometimes confusing things, you can do with functions. Recursion is when a function calls itself. In order to understand how that might work, let's look at something that is not recursion, but is a series of functions that we've built in order to take a number to an exponent. For example, 4 to the 3rd power. We have an initial function beginning on line 2 that takes the number and the exponent, it examines the exponent on line 3 to see if it's equal to 0, and if so, it returns the value 1. Otherwise, it multiplies the number that was passed in times whatever it gets back by calling this second function. What it passes to the second function is the number and the exponent again, but reduced by 1. So, if we were taking 4 to the 3rd, we would call func2 with 4 and 2 because we've reduced it by 1. In func2 we do the same thing. We check to see whether the exponent is equal to 0, and if so we return 1, but it's not because we passed in 2. So, we multiply 4 times whatever the result is of calling a third function, again reducing the exponent by 1. So, now we're going to pass in 4 and 1, and as you might guess, we're then going to pass in 4 and 0. At that point, the exponent is equal to 0, and will return the value 1. We'll multiply number times 1, that's the result we got. So, that's 4 times 1 is 4, we'll pass that 4 back up here, we'll multiply 4 by 4, which is 16, we'll pass the 16 up here, and we'll multiply 4 by 16, and we'll get 64, which is the correct answer of taking 4 to the 3rd power. This is ugly, but it works. However, functions 2, 3, and 4 are doing exactly the same thing as function 1, and there is no reason to create all those extra functions. Function 1 can call function 1, and so that's what we're going to do. We're going to take out all of these extra functions and instead call function 1 from function 1, that's the recursion, and what will happen is it will say return num, which is 4, times, and it will call function 1 again, but this time with 2. That will come through and say okay multiply 4 times call function 1 again, this time with 1, and then with 0. When it hits 0, it'll return 1, and that'll cause all of the functions to return back out just as we saw before. And, once again, we'll get the answer 64, which is the correct answer. What's nice about this is that we can put in much larger exponents and not have to have a series of 10 or 12 functions to support them. We can put in 2 and 10, and 2 to the 10th is in fact 1024, so we get the correct result. One thing to remember about recursive functions is that anything you can write recursively, you can also write iteratively. So, rather than writing this as a recursive function, we could instead write this non- recursive version in which we set an initial return value to 1, and then we have a for loop where we count from 0 to whatever the value of the exponent is, and we multiply the return value times itself times that number, which is very much the way we think about doing simple exponents. And, of course, we get the same answer when we call the non-recursive version as we do when we call the recursive version. The recursive version is somewhat smaller, somewhat more elegant. The one danger you have with recursive functions is because they are building up one after another on the stack, you can run out of memory if you put a very large number in, but with modern computers, that's not much of a problem.
Data and Objects
In this section, we are going to consider the important topics of objects and collections. Objects can be thought of as collections of properties. Properties can be designated for an object and additional properties can be added on the fly. If you attempt to reference a property that doesn't exist, the value returned will be undefined, so there's a lot of flexibility in how objects work. Objects can even have functions, which are often called methods when they belong to an object. We're going to take a look at how to create objects and add properties to objects, and how to retrieve properties using both dot notation and array notation, and how to delete properties as well.
Typically, objects are created as a collection of properties. Here I've used an object to gather information about my dog. I can use this information in order to retrieve specific properties from the object. And so, for example, I can extract the dog weight into a variable, put that into an alert, and when I bring up the page, it tells me the dog weight. I can also add properties on the fly. Let's comment out the alert. And say that I decide to add a disposition to the dog. And I can simply assign to that new property, and it's as if I had added that property all along. And I can retrieve that property, and notice that WebMatrix is able to use the information in that property even though it was assigned on the fly to fill the IntelliSense, making the programming much easier. And we can run that and see the alert that says the disposition that we added on the fly. If I attempt to retrieve a value, or more accurately a property that is not part of the dog, my first clue is that it's not going to show up in the IntelliSense in WebMatrix, although you may be working in a different environment that doesn't have IntelliSense. But if we try to display that property, what we get is an undefined value simply indicating that value is not defined for that collection or for that object. A key aspect of objects is that the properties are mutable, that is to say they are changeable. And so I can come in and say dog.weight = 15, and then I can say var dogWeight2 = dog.weight and alert on that, and it's going to come up and not say the original 12, but rather the modified value of 15.
There are many ways to define an array. For example, I can define my array that I'll name empty simply by putting in square brackets, and now I have an empty array that I can add items to. Of course, that does change the meaning of the name of the variable empty, but nonetheless, I can say, for example, empty offset 0 = 1, and empty offset 1 = 2, and now empty is not so empty. And if I say alert(empty), and we run that application, we get 1,2, the contents of the formally empty array. Another way to define an array is to define the members when you create it. And so I can fill in my primes array debating whether 1 is a prime, and then I can, at any time, extract from my array using offset notation. So, the thirdPrime is going to be at offset, and I'm going to leave that as a question for a moment. And the way you figure that out is 1, 2, 3 is the third prime, and that's at offset 0, 1, 2. Remember that the third prime will be at 3 minus 1 because we have 0 offset. And we can see that as well. Let's comment out the earlier alert and run this program. And there's our third prime. Arrays do not need to have uniform types in them, so I can create an array and set it to have the value 1 and hello and false, and that's a perfectly valid array. And I can extract any of those values using the offset. So, here I'm going to extract the final value and set that as truth, put in an alert, and let's run the application. And sure enough if comes up false because that was the third member of my array it offset to. Remember that the length of an array tells you how many members are in the array, not the highest index of the array. Here I've set my array length to myArray.length, getting the length property from the array, and I've put that value into an alert, and sure enough it comes up and says 3, which is the length of that array. You can add to arrays after they're created, and let's create a small function that uses that capability. We'll call our function range. It will take one parameter, which is the max. That's the number that we want the range to go up to. And in the function, we're going to have a return value, which is an empty array. We'll then add a for loop to populate that array. Let's take a quick look at the for loop. It's going to create a counter called I, which it will initialize to 0, it will count while I is less than max, incrementing I each time through the for loop, and it will set the Ith offset, so first 0, then 1, then 2, equal to I timex 2. It will then return that value. Notice, by the way, that the for loop uses the counter variable I. Using I and then J and then K as counter variables is an old programmer tradition going all the way back to Fortran where those were the required identifiers for counters. And for small loops, it is very much the tradition to continue to use I, and if you have a nested for loop, then J, then K as your counter variables. This is very much akin to why the roads in Boston are so twisty. They were built on old cow paths. Old traditions die hard. We can see the result of this method by calling alert and passing in range and giving it a value, let's say 5 for its maximum, and then let's run this application. And sure enough we get five values.
Arrays Part 2 Introduction
Arrays have a few methods of their own. Push adds a member to an array, pop returns the last values in that array and removes the value, and it is possible to iterate over an array using a for loop. Let's take a look at these in action.
Arrays Part 2
Let's return to our range of max. In the for loop, we assign a value to the offset inside the array. Rather than explicitly assigning to each individual offset, we can instead use the push method. We take the value that we want to assign to the end of the array and put it inside the parentheses for the push function, and now it will push I times 2 to the end of the array each time through the for loop. Let's run that using a range of 5, and we get 0,2,4,6,8. That is five values exactly as we expected. Let's set the variable last equal to what we get from pop on our array, and we can alert what value we got back. And then we will alert what's in the range. Let's see if we can make sense of what we get from that. The first thing we get back is 8. That was the last value added, and so that's what gets popped off the array. Because that was popped off the array, our array is now shorter, and it's just 0,2,4,6. And that's because it's being popped off before we see it. As noted earlier, we can use a for loop to iterate through an array. The function range, once again, creates our array. We're going to take the result of calling range, passing in 5, and assign it to myArray. Remember what is being returned is an array. And then we're going to iterate through each member of that array in a for loop where we initialize I to 0, and we count up as long as I is less than the length of my array, and we're going to display each value in turn by using the offset operator into the array. When we run this, we see 0 and then 2, 4, so each member of the array is being displayed in turn all the way through 8. As you see, arrays can be a powerful way to put together collections, to add to those collections, and delete from those collections.
As we noted, you can begin a string with a double quote or you can create a second string and use a single quote. Whichever one you use leaves the other to be put inside the string. For example, in the second one, I've used single quotes so I can put double quotes around the word lazy, and those double quotes will not be read as ending the string. Thus, this is a perfectly safe string to alert, and the double quotes appear in the string. The same thing works vice versa obviously. Another thing that you can do if you run out of the option of single and double quotes is you can escape quotes. If I wanted to put double quotes into my double-quoted string, I can use the backslash as an escape meaning this quote should be part of the string, not the end of the string. And I can do that on either side of lazy. And now, even though I'm using double quotes, I can put double quotes into the string itself, and we can see that by running string1. So, there are a couple ways to accomplish the same thing. There are a number of useful escape characters. One of the most common is backslash N for new line, and that inserts a new line into that string, which we can see in the alert box. Be careful using new lines when you're using the innerHTML as they'll be ignored by the HTML, but we do see them in the alert box quite cleanly.
Strings Part 2 Introduction
In the previous demo, we noted the use of escape sequences. Escape sequences begin with the backslash such as backslash N for new line. There are also a number of operators and methods available for manipulating strings. One of the most common is the plus operator, which when used for strings, is used for concatenation. That is, concatenating two strings together into a single string. There are other operators for string. Some of the most popular are charAt, which gives you the string or actually a single character as a string at an index, indexOf(string) pass in a substring and find the index, split, which cuts a sting into an array, and slice which copies out a piece of the string. Let's take a look at a few of these to see how they work.
Strings Part 2
Here we have two perfectly valid and happy little strings. String1 says, "The quick brown fox jumps over the lazy dog." String2 says, "and lived happily ever after." We can concatenate these into a single string by using the concatenation or plus operator, and then we can look at our new string using an alert box. And you notice that as far as you can tell, that new sting is a perfectly normal string, nothing special about it even though it was concatenated from two smaller strings. One useful thing that you can do with strings is split them into arrays, having each word be a separate entry in the array. The way you do that is to take the string and call split on it and pass in the character that the string should be split on. In this case, we'll pass in a space. What it's going to do is take the string, and every time it sees a space, it's going to break that entry into an entry in the array. We can see that again with an alert. Let's go ahead and run that. And notice that each word is a separate entry in the array. Notice also that lazy, which was in double quotes, is in the array with its quotes because the separator was a space and the space is on either side of the double quotes. You can use the indexOf function to find the location of a substring within your outer string. Here I've declared a variable, indexOfBrown, and I've filled it with the value returned by calling indexOf on newString and passing in the characters B,R,O,W,N. It's going to find the index of where brown appears in that string. Let's see what the alert says. It says that it's at index 10. If we go back and look at our string, 3, 4 for the space, 6, 8, 9, 10 for the space, and it is, in fact, begins at offset 10, which is exactly what we wanted. If we then go ahead and get the indexOfJumps, we can use those two indices with the slice function. The slice function wants the index at which to begin cutting and the index at which to end cutting. So, we're going to give it the index of where brown is and the index of where jumps is, and it will begin cutting at the B for brown, and it will end just before the J in jumps. Let's add an alert to see myFox and run that. And sure enough, we get brown fox. And so we've been able to extract that substring by using the slice function. As noted, there are a large number of functions for manipulating strings, but we're going to go on and talk about an even more powerful way to manipulate strings, which is with regular expressions.
Regular Expression Introduction
Jesse Liberty is a Senior Consultant at Wintellect, where he specializes in Xamarin, Azure and Web development. He is a Certified Xamarin Developer, a Xamarin MVP and a Microsoft MVP.
Released20 May 2013