What do you want to learn? Leverged jhuang@tampa.cgsinc.com Skip to main content Pluralsight uses cookies.Learn more about your privacy JavaScript From Scratch by Jesse Liberty Learn JavaScript with no prior programming experience Resume CourseBookmarkAdd to Channel Table of contents Description Transcript Exercise files Discussion Learning Check Recommended Introduction Introduction Hi, this is Jesse Liberty from Pluralsight, and welcome to JavaScript from Scratch. You've chosen to learn what is arguably the most popular programming language in history. JavaScript is the language of the web, and it's also one of the primary languages of Windows 8. JavaScript is nearly ubiquitous. You find it across operating systems and across browsers. We make no assumptions about prior programming experience, and I'll be teaching JavaScript from scratch from the very beginning through everything you need to know to be productive. In order to follow along in this course, all you need is a browser running on virtually any operating system. We're going to assume you're running on either some form of Windows or the Mac or Linux. You may also want to have a text editor such as Notepad or Notepad++ or any of a number of other text editors that are designed for JavaScript or simply just text editors. Most of what we will be doing will be through example programming as opposed to through lecture and slides. We're going to get your hands on as quickly as possible and keep your hands on the keyboard working on JavaScript and JavaScript problems. Over the coming modules, you will learn all there is to know about the best of JavaScript, coding, good coding practices, and becoming an excellent JavaScript programmer. I have on my bookshelf two books on JavaScript. One is comprehensive and it's over 1200 pages. The other is called JavaScript: The Good Parts, and it's under 150 pages. The essentials of JavaScript, the parts that you use everyday and the parts that you want to use, are not that complex or large, and we'll be able to cover it in this single course. In this introduction, we've discussed very briefly how popular JavaScript is and why you might want to learn it. We've reinforced that you need no prior programming experience to take this course, and that you can be working on any PC with any operating system using any browser. Our focus is going to be on code. Fundamentals Introduction In this module, we'll be discussing the fundamental techniques and categories, types, ideas, and concepts that you'll be using throughout your work in JavaScript. One of the questions that perplex new JavaScript developers is how to begin to write JavaScript programs. Where do you actually put the code? There are two options you have for getting started in writing JavaScript. The simplest and most ubiquitous available through any browser, whether you're online or off, is to write script into an HTML page and run that script inside your browser, and I will show you how to do that right away. The second possibility is to use one of the JavaScript helper sites available online that simplify this process. Let's start with the first option, Writing Script in an HTML Page. To begin, you need to open Notepad or a similar text editor. Inside Notepad, you want to create a very simple HTML file. Put an HTML tag at the top and a closing HTML tag at the bottom. Inside, optionally, you may create a header section and you may want to create a body section. Within the body section, you can place any HTML that you would like to have appear on the page. What's critical for our purposes is that you're also going to add script tags, an open script tag and a closing script tag, and between those two tags, you will put all of the JavaScript that you'll be creating. For example, we can take advantage of the alert function and we'll be discussing functions in detail later in the course. What alert does is it pops up a message box, and we're going to put into alert the values 3+5. End that with a semicolon. And I will be explaining all of this in detail as we move through this course. But here we have a very simple HTML page with script tags, and inside the script tags some very simple JavaScript. Let's save this file, pick a directory, find the place that you'd like to save it, and give it a name. We'll name this Demo1.html. You want to have an .html or .htm ending to indicate that this is an HTML page. Next, open your browser of choice, and any browser will do. Let's start in this case by using IE. From the menu, we're going to navigate by saying Open and then Browse, and browsing to that same file, Demo1.html, and opening that file and clicking OK to open it. That will open the page. There is our Hello. Now, our pop-up did not fire because Internet Explorer restricted this webpage. We can say Allow that blocked content, and now our pop-up comes up, and you remember its contents were 5+3, and it displays that as the sum or 8. The walkaway from this is that you can create a very simple HTML page, put script in, and for example, we can change our script to say Hello JavaScript. Save that file, return to our browser, refresh the page, and once again our message box contains the contents of the alert. So, that's one way to run your JavaScript. There are also helper sites on the web that can greatly simplify running JavaScript if you have an internet connection. For example, one site that I like is Plunker. Plunker comes up and it has on the left here the code, and on the right the results, and notice that it has three files already set up, index.html, style.css, script.js. Here's the HTML file, and it says my script is in a file called script.js. Notice this source equals script.js, and that says don't look in this file for the JavaScript, but instead look in the file script.js. We can go to that file, script.js, and put our code in there. And so once again, we can say alert 5+, there's the 5, 3, and there's the 8. And we can come back here and we can change it to say alert Hello Plunker, and as soon as we get out of the string, it fires again. So, you can see this is very quick and a very easy way to work with your JavaScript, and you can just leave index.html alone and put your JavaScript in and try it out here. We'll be using Plunker quite a bit in this course and you'll see it at work, but anything we do in Plunker, you could also do in a simple HTML file. Fundamentals of JavaScript You are now at the hardest part of the course of learning JavaScript, and that's the part where you need to get started. It can seem as if you need to know everything before you can know anything, before anything can be in context or understood, you have to understand everything else. In order to get through this difficult part, you must become comfortable with partial knowledge knowing that all of the concepts will be filled in as we go, and some of these are new concepts that can take a while to wrap your mind around. Don't let any of this cause you alarm. It gets easier as we go. Let's begin by looking at the building blocks of JavaScript. The first thing to consider is numbers. In some programming languages, numbers are divided into all sorts of subtypes such as integers and doubles, but in JavaScript a number is a number is a number, and numbers are just what you would expect, 5 and 6.4 are numbers. All of these are legitimate numbers. Strings are what normal people call text. They're anything that appears between quotes. We'll be using strings quite a bit. Here you can see we've added two strings. One says this is a string. The other says this is a second string. Notice that you begin and end a string with quotes. If you want to use quotes within the string, you must use a special character called an escape character, which is a backslash. By putting in the backslash, you signal to JavaScript that that is not the end quote for the string, but it's a quote within the string. We can see that this works by placing this string in an alert box, and you can see that the double quotes are preserved because of the escape character. These numbers and these strings each return a value or evaluate to a value. They evaluate in the case of the numbers to the number itself, 5, 7, 6.4. Anything that evaluates to a value is referred to as an expression. Each of these values disappears the minute you move past it. There's nothing holding onto these values. That's what variables are for. Variables begin with the key work var, that's followed by the name of the variable, and then you assign to that variable whatever you want, whatever value you like. So, for example, we could say myValue = 5. We could create a second variable called mySecondValue and assign to it the sum of 7 + 9. If we create a third variable and assign to it myValue + mySecondValue, what's going to happen is that my second value will be evaluated to 16, my first value will be evaluated to 5, and so the new variable, my third value, will evaluate to the sum of those values. We can see that by adding an alert and passing in, if I spell it correctly, myThirdValue. Variables can also be created to hold strings, and again, you can have multiple such variables. You can't add, subtract, divide or multiply strings, but you can concatenate them, and we use the plus operator to do so. Here we've created two variables to hold myName and myLastName, and then a third variable to hold the concatenation of the two. Now, they'll be smooshed together if I don't put a space between them, so let's put a space here and then add myLastName. Let's see how that looks by adding an alert. And as you can see, it has concatenated the two strings and the space as we desired. We've taken a preliminary look at variables, and we even saw a few operators at work, the plus operator and the concatenation operator, and, of course, there are many more operators. Operators that work on two values are called binary operators. The plus sign is a good example. When you say 5 + 7, that's a binary operator because it's operating on those two values. There are also unary operators that operate on just a single value, and we'll see that as we go. We discussed expressions, which evaluate to a value. We've also been working with statements. A statement is any set of expressions that has an impact on the program such as assigning a value to a variable, calling the alert function, and we'll be looking at statements throughout the rest of the course. The meaning of statements will become clear as we use statements to write our programs. Let's take a moment to say a quick word about whitespace. Here on line 19 I've written a typical statement. It has the keyword var, then the name of the variable, an equal sign, 5, a plus operator, 9, and like all statements, it ends with a semicolon. Let me note that semicolons are not strictly required at all times, but we will be using semicolons to end all statements in this course. The space between val and the equal sign and the equal sign and 5, the 5 and the plus, all those spaces are called whitespace because when it's not highlighted, you can see through to the white behind them. You can put as much whitespace as you want without changing the meaning of the statement. This statement now has exactly the same meaning as it had before. Take the value 5, add it to 9, and assign that 14 to the variable val. You can also remove whitespace in most situations. So, for example, I can remove all of this whitespace and smoosh all of these together. However, I cannot remove the whitespace between the keyword var and its name val because there'd be no way for JavaScript to tell that that's the keyword var, it's now varval, which could be anything. It could be an existing variable. The rules about where you can remove the whitespace become very obvious as you're programming, and it's not a mistake you're likely to make. I do encourage you to use extra whitespace so that your code is easy to read without, of course, using absurdly excessive whitespace. Note that new lines and tabs are also considered to be whitespace. That concludes the fundamentals. We have mentioned functions, and we will have an entire section on functions, and we haven't yet mentioned, but we will be talking about objects as well, but that's for later in the course. Summary In this module, we took a look at how you can write your JavaScript programs either using a simple text editor and you're browser or one of the helper online programs. We also looked at numbers and strings, as well as variables. We took a look at some simple operators such as the addition operator, and we'll be looking at more in coming modules. We looked at expressions and statements, and we briefly looked at whitespace and how you can use whitespace to make your program more readable. Program Flow Introduction In the fundamental section, we looked at individual JavaScript expressions and statements. Let's take a look now at stringing together a series of statements to create more of a program. We'll also take a look at how we can use special keywords to interrupt the flow or redirect the flow of the program, allowing us to add logic to our program depending on prevailing conditions. If Statements Unless told to do otherwise, a JavaScript program begins at the first statement, proceeds statement by statement to the bottom, and then stops. However, that typically makes for very rigid, if not, boring programs. One way to change the order of the execution of statements is with an if statement. An if statement says if the conditions we're testing evaluates to true, then execute the next statement. Otherwise, skip the next statement and go on from there. Statements can be put together with braces into blocks and treated as a single statement. Let's take a look at how all of this plays out with a simple program. For this, and many of the other programs that are upcoming in this course, we're going to use the WebMatrix tool, which is a free tool from Microsoft. It's considerably more than we need, but it will allow me to save the examples and make them available to you. You can download this from Microsoft, just search for WebMatrix. It's a free download. Once it's installed on your machine, it will come up and offer to create a new site or to let you build a site from one of its templates. We're going to choose templates HTML and Boilerplate. Again, that's going to create a lot more of a site than we need, but it is going to give us the functionality we want for JavaScript. Let's come over here to Files, and notice we have JavaScript folder. You can ignore all the rest of this. Open up the JavaScript folder and find script.js. Sure enough, there's a script file that we can work with. Let's just double check that this is going to do what we need by putting in a simple alert, and notice that we get IntelliSense help, and that's going to be a big help as we go along. For example, IntelliSense here says that alert takes one parameter, which is the message. We'll put in the message hello, and then we will come over to the Run button and run our program, and sure enough, the browser comes up and the hello box comes up. That's all we need to be able to proceed. Now, we were going to take a look at the if statement. The first thing that we want to do is prompt the user to enter their age. We need to create a variable to hold the age that the user is going to give us, and prompt returns a string. So, we're going to call our variable ageAsString and then we're going to assign that to calling prompt, which notice prompt is lowercase, and JavaScript is case sensitive. That means there's a difference between prompt with a lowercase P and prompt with an uppercase P. The function that we need is prompt with a lowercase P. Let's open up prompt and it tells us that it needs two parameters, the message and the default. Now, our message is, "What is your age?" and our default will just be an empty string. The default is what's put into the message box for the user to override. Once we get back the age as a string, we can convert that age into a number, and so let's create a second variable called age, which will be equal to whatever we convert ageAsString into as a number. We do that with another function called the number function, and we pass into number function the ageAsString, and that's going to do the conversion for us. To make sure that we got the right thing, let's alert the age just so we can be sure we have it. Let's run the application. Up comes the prompt. I'll lie and say that my age is 35, click OK, and it comes back as we expect with 35. Now, notice that this program proceeds line-by-line, and each line is executed. I do have the opportunity here to put an if statement, and what I'm going to ask is if, and if statements always take parentheses, age is less than 40, and if it is less than 40, I'm going to put up an alert that says, "Oh you're so young..." In any case, whether or not the age is less than 40, I'm then going to put up an alert that says "Thank you" and that way we'll know we've hit the end of the program. Now, let's look at the logic of this. It's going to execute the first statement and ask for the age. It will then execute the second statement and convert that age into a number. The third statement is an if statement, and if the age is less than 40, then line 5 will execute. These braces simply create a single statement out of however many statements I put between them, but it's good programming practice even if you only have one line to put the braces, and I'll explain why in just a moment. In any case, whether or not this if statement executes line 5, line 8 will execute. We can see that by putting in ages both under 40 and over. Let's start by running and putting in an age under 40, 35, click OK. Oh you're so young comes up because the if statement was true, and then the Thank you comes up because that's the end of our program. Now, remember the age is under 40. Let's put an age of 40 or greater. In fact, we can put the age of exactly 40 because 40 is not under 40, and notice it goes directly to Thank you; skipping the Oh you're so young. That's the basics of the if statement. Let's save this file, and we'll save that in the JS folder as ageif, actually let's call it ifStatement.js, and we'll save that away. Braces 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. If/Else 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. For loop 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. Break Statement 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. Switch Statement 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. Summary In this module, we looked at the fundamentals of program flow. We noted that JavaScript is a case sensitive language, and we noted that you can use braces to create a block of code that will be treated effectively as a single statement. We looked at how to interrupt the flow of the code using conditional statements such as if, if and else, and else if for more complex conditional. We also looked at the while loop and the do while loop for taking action while a condition is true. We looked at the more complex for loop that lets you set up a starting condition, a test condition, and a change condition, and we looked at the break statement for breaking out of loops. Finally, we looked at the most complex of the conditional statements, which was the switch statement. That concludes our introduction to JavaScript programming flow, and we're ready to tackle some more advanced topics. Truth Introduction In this module, we examine the meaning of truth, at least from the perspective of JavaScript. JavaScript has a type called Bool, and Boolean values are limited to true and false. Those are the only two possible values for something of the Boolean type. There are Boolean operations, and, for which you use the double ampersand, or, for which you use the double pipe or vertical line, and not, for which you use the bang or exclamation mark. Many values are falsy, that is they evaluate to false. The values that do so are null, undefined, NaN or not a number, the empty string, and 0. Writing 0 equal false will return true. Everything else is truthy. So, if it's not a falsy value, it is a truthy value and will evaluate true. JavaScript also differentiates between two types of equality. The double equal sign checks for simple equality. Zero equal equal false will return true. The triple equal sign looks for exact equality. Zero equal equal equal false will return false. Let's take a look at some of this in action. Boolean Values Let's have some fun playing with Boolean variables. For example, I can put in a variable called isMale, and since I am male, I'll set that to true, and have a second variable called isOld, and since I'm also old, I'll call that true. Then I'm going to variable called isOldMan, and I will set that to isMale and isOld. What I have done is turned isMale into a Boolean variable and set its value to true. I've done the same with isOld. Here, I'm using the ampersand, that is the and operator. The and operator returns true if both sides of the expression are true. So, it will return true if isMale and isOld are true. Since they're both true, isOldMan is also set to true. And we can see that by running an alert. If I change isMale to isFemale, which will be false, then I can test isFemale and isOld. IsFemale is false, and so the and operator will return false. What's interesting here is that the ampersand operator will short-circuit the evaluation because an and requires that both sides be true. This is evaluated left to right, and when isFemale is evaluated as false, it returns false immediately, and isOld is never evaluated. This can be used in programs so that you short-circuit on purpose, and if the left side of your equation is false, the right side is never evaluated, which can be handy when the right side might be, for example, null. Let's change our operator to or. That's two pipes or two vertical lines. Notice that we're now getting a true return. What is the meaning of this logic? Well the meaning is we've assigned to isOldMan give me back the value if isFemale is true or isOld is true. Since one of them is true, isOld is true, the entire thing evaluates to true. Now, notice that as an English sentence, this no longer makes sense because it's not true that it's an old man. And that's a reminder that our variable names need to be used very carefully. So, here I've repaired the variable name to make a little more sense. The or statement also short-circuits. It will return as soon as it finds something that's true. IsFemale is false, so it will go on to evaluate isOld. That's true, and or returns true if either side is true. If we reverse the order of evaluation, this in no way changes the results. We're still going to get true, but it does mean that it short-circuited. It evaluates isOld, finds out that that's true, and never goes on to evaluate isFemale. Let's put a comment marker in front of the alert and in front of line 5 as well. Comments are just lines that are ignored by JavaScript, and that allows us to keep these in the file without them being evaluated. We can now set a variable isMale equal to not isFemale. The not operator is a unary operator. It operates on one expression, and it reverses its truth or falseness. Since isFemale is false, the not operator will evaluate this entire expression is true, and isMale should evaluate as true, which sure enough it does. Truthyness We spoke earlier about falsy and truthy values. We can test whether 0 is falsy by typing alert and then setting the test 0 equals false, equal equal false. When we run that, if 0 is falsy, this will evaluate true, and sure enough it does. The distinction between equal equal and the three equal signs, equal equal equal, is that the three equal signs requires an exact match, and it's not true that 0 exactly matches false. Its falsy, but it's not false. In many languages, while 0 equals false, 1 equals true. We could see whether that's true by testing it, and this leads to one of the most important lessons of this entire course. When in doubt, ask JavaScript. This is how we ask does 1 equal false. The answer is no. Now we can ask well, does 1 equal true, and the answer is yes. One is equal to true. Before we leave, I'd like to talk about the conditional or ternary operator. A unary operator works on a single value. For example, on line 1, we assign the value 5 to the variable x. On line 2, we use the unary operator ++, usually called the increment operator to increase the value of x by one. This is exactly the same as writing x plus equal one or writing x equal x plus one. All three will do the same thing. When we run this, because we have incremented the value of the x, it now has the value of 6. That is a unary operator. Here we've changed the program. We've assigned values to two variables, x and y, and on line 3 we used the binary operator plus to add the value of x and y and then assigned that to z. And, of course, when we alert on z, we get the value of 11. I've changed the program one more time, this time to use the conditional operator. The conditional operator is sometimes called the ternary operator; ternary meaning it has three terms, and this is the only operator that does. The first term is the condition to test. In this case, x is less than 10, and that's followed by a question mark. The second term is the value to return if the condition is true, so we will return x if the condition is true. That's followed by a colon. And the third term is the value to return if the condition is false. As shown, y is equal to 5. If we set x to 14, y would be equal to 10. This ternary operator is exactly the same as an if else statement. Line 2 is exactly equal to lines 4 through 12. Set up y as the variable to which you will assign the result, test your condition is x less than 10, if the value evaluates to true, assign x to y, otherwise, assign 10 to y. Summary 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 Introduction Functions are the heart and soul of JavaScript. In fact, they are the centerpiece of virtually all programming languages. If it weren't for functions, your program would be one huge, complex, unreadable file with lots and lots of duplicated code. Functions allow you to break your code up into smaller units, many of which can be called repeatedly to do work on behalf of other parts of your program. All of this is very abstract, but when we look at functions, you'll see that it's pretty straightforward. A function is what we used to call a subroutine, a little block of code that you can call, pass values into, get values back out of, and call repeatedly as needed. In discussing functions, you can imagine that your program is a series of statements. JavaScript begins at the first statement, executes it, moves on to the second statement, executes it, and then it sees function 1. At that point, processing stops right where it is and switches over to function 1. Each statement in function 1 is executed until we hit a return statement. At that point, we return right where we were and resume with the next statement, statement 3. The statement after that is a call to function 2. So, once again, we depart to the new function, execute the statements in the new function, and return, possibly returning a value, and pick up right where we left off with statement 4. Now, of course, it can be more complicated than this. Function 1 could call function 1A, and then we would return to function 1 and then return to our original code, and we can have any number of nesting and expansion from one function to the next. Function Basics 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. Functions Return 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. Hoisting Functions in JavaScript support hoisting. Hoisting means that your function is lifted as if to the top of the file. Here's a familiar little bit of code. The function is defined, is named add, then we assign to z, call to add passing in 3 and 5, and we output the value of z. It turns out we could call add even before it's defined. That is to say we can call it up here, and that will work equally well. And the reason is that this function is hoisted to the top of the file behind the scenes. This is useful when you have one function that calls another and you do not want to have to worry about the order in which you declare your functions. Functions and Scope To fully make use of JavaScript functions, you must understand the concept of scope. Scope has to do with what variables are visible at what time. We're going to look at the scope that is created by functions. We're also going to look at nested functions and understand how nested functions are in the scope of their outer function. Along the way, we'll reinforce the idea that braces themselves do not create scope, only functions create scope. We'll also look at global versus local values. When we declare a variable that is not within any particular function, that variable is said to be at global scope. That means that it is globally available to all functions. If we now create a function, and we'll call it celsiusToFarenheit, and it will take one parameter, which will be the temperature in Celsius. We'll then create the Fahrenheit temperature by taking the temperature that's passed in and multiplying it by 9/5 and adding the constant, which is 32. First, let's make sure this works. So, we'll call the celsiusToFarenheit function, we'll pass in 100, set the result to the innerHTML, and we see the result is 212, which is exactly right. The boiling point in Celsius 100 is equal to the boiling point in Fahrenheit of 212. Notice, and this is the important point, that the variable constant was declared outside of the function, and yet the function had access to it. That's why we're saying that constant is at global scope, it's available to all functions. However, if we were to declare local variables inside of the function, while these will certainly work because they are still within the scope of the function, if we try to access them outside of the function, those values are not defined and come back as null. So, to reiterate, variables declared outside the function at a higher level or a global scope are visible inside the function, as are variables defined inside the function and parameters passed into the function. What's not visible are variables defined inside the function when you are no longer in that function, when you're outside at global scope. Let's examine this alternative block of code. On line 3, we declare a variable x, set its value to 15. On line 4, we check if x is less than 20, and if it is, which it is, on line 6 inside the braces of the if statement, we declare a variable y equal to x. On line 9, we try to use that variable y by assigning it to z, and sure enough that works. In many languages, braces create scope, but not in JavaScript. As far as JavaScript is concerned, that var y is in the same scope as x, the global scope. The only thing that creates scope in JavaScript is functions. Nested functions 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 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 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. Summary In this module, we looked at functions. Functions are effectively subroutines, little snippets of code that you can call and call again, thereby cutting down on redundancy in your code and making your code more modular and easier to understand. Functions can be named or they can be anonymous, and they can be assigned to variables and called through the variable. Functions can identify parameters, although they are very forgiving about the number of arguments you pass in and how they match up with parameters. Send in too many arguments, and the extra arguments are ignored. Send in too few arguments, and the missing parameters are set to undefined. We talked about the fact that functions declare a scope and are the only way to declare a scope in JavaScript. Variables that are defined outside the function at a higher level are available inside the function, but functions can create a closure over those variables so that they are guaranteed to be available when the function runs. Finally, we talked about recursion in which a function calls itself. Data and Objects Introduction 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. Objects 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. Arrays Introduction A special kind of object is an array. Arrays act as collections and are really the only collection class in JavaScript. The length of the array is the number of items in the array, but remember that arrays are 0 offset, which means the first member in the array is at offset 0. Therefore, the last member in the array is at length minus 1. The push command adds a member to an array. The pop returns the last value in the array and removes it from the array. We can use for loops to iterate over an array. Arrays 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. Strings Introduction Another key object in JavaScript programming is the string. We've seen strings already. They're simply quoted characters that are used for text. They can, in fact, be quoted with either single or double quotes, and the advantage of that is that by using single quotes, you can include double quotes inside the string or vice versa. Let's take a quick look at what that implies. Strings 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 As noted, regular expressions can be used to find or extract or manipulate substrings within a string. We'll focus on searching as that will illustrate much of how regular expressions work. Strings have a search function that take a regular expression. Regular expressions are marked between forward slashes. Whatever you put into the area between the two forward slashes is a regular expression, and it will attempt to use that regular expression to match the substring. You can put in literals. For example, I can put in the work quick, and notice that even the editor is showing me that it's going to match on quick from the quick brown fox. You can also use special characters to indicate what you're looking for. For example, I can put in A-Z in square brackets, and that means find any letter A-Z, and then I can put an asterisk afterwards, which means that I'm looking for any number of those letters A-Z. What I will get back from my search is an offset. In this case, it's going to look for any number of characters that are in the format A-Z, and since the very first character matches, I should get back an offset of 0. And sure enough, I do. I can modify my search by putting the number 5 in curly braces saying I'm looking for five letters in this set of A-Z, and surround that by slash B, which means I want it on a word boundary. What Regex is going to do is come along and say well, I've got three characters here and then a word boundary that does not match. Oh, I've got five characters here and a word boundary that does match. So, we should see an offset of 4, and sure enough, we do. Now, the syntax to this is a little bit obscure already. Let's take a look at a common regular expression. Here the string that we're searching is, "my zip is 01720 what is yours?" And the way we search for that is with a regular expression very similar to the one we were just using except we're searching for a value in 0-9. So, even if it finds a five letter word, it's not going to match on that, it's going to match on the five numerals. Let's run that. And sure enough, it says that it's at the 10th offset, which is where the zip code is. This does work, but if I have plus four zip code, then it's going to be hard to find the end of the zip code because this is not a complete description of the zip code. Let's look at a more complete description of the zip code. Here we have something that looks a little bit more like a typical regular expression, and what it's saying is to find five characters and then optionally a dash followed by four numeric characters on a word boundary, and this will match as well. A question arises right away is to how you would possibly create one of these, and there are two answers to that. There are some folks who do these are all day and are quite comfortable with them, but for us mere mortals, we're going to want to use a tool. One excellent tool is called RegexBuddy. Let's bring that up. RegexBuddy is taking a look at this same regular expression and breaking it out for me and telling me exactly what each token means. So, we've got assert position at a word boundary. That's the first token. Then the second token here in orange, 0-9. It's saying match a single character in the range between 0 and 9. Then match exactly 5 times. That's this blue character. And you notice that it's color coded. I can click on any token, for example, the five, and say explain token, and it will take me to the help for that particular token and give me even more assistance in understanding it. I can also use RegexBuddy to create new regular expressions and test them. And most important, I can go to the library and pick out from their large library of regular expressions a regular expression that matches whatever it is I'm looking for. RegexBuddy is very powerful, but it's not free. There are also online services such as RegExLib.com. We can enter into the keyword zip code and search, and if I scroll down, I can narrow of course, but if I scroll down, I can start to see lots of different zip code regular expressions depending on whether I want a US zip code or something that's going to match internationally and so on. And you can see that for each one they provide the pattern and a description, they give an example of what matches and what would not match, and you can take these and put these into your code or you can take these and drop them into RegexBuddy, and then ask RegexBuddy to explain each of the steps in the regular expression. Regular expressions are not an intrinsic part of JavaScript. They cut across many programming languages, but they can be very useful in JavaScript for manipulating strings. Summary In this module, we looked at objects and noted that objects are essentially collections of properties. Objects can also have functions. One special type of object is an array, which is the basic collection class for JavaScript, we looked at other special objects such as strings, which have functions to manipulate their values, and then we looked at regular expressions, which are a powerful string matching mechanism. Course author Jesse Liberty 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. Course info LevelBeginner Rating (3158) My rating Duration1h 52m Released20 May 2013 Share course