The Basics - Getting Good with JavaScript (2011)

Getting Good with JavaScript (2011)

The Basics

Here's where we actually get down and dirty; in this chapter, we're going to cover the nuts and bolts of JavaScript: all the little seemingly-unrelated pieces that will build the core of your JavaScript knowledge.

Variables

In a minute, we'll be discussing data types in JavaScript, but we need to cover variables first. Depending how you look at this, we might be putting the cart before the horse, but we'll figure this all out. For now, know that we have values like text and numbers in JavaScript.

Variables are basically labels that you give to your values. The variable points to the place in memory where the value is stored. So, how do you make one of these variables?

Example 2.1

var name = "Joe",

age = 45,

job = "plumber";

alert( name ); // Joe

There are several things to notice here: firstly, when creating variables, you must put the keyword var before the variable name. Next comes the variable name. You can name your variables whatever you want, within these boundaries: you can use any combination of letters, numbers, dollar signs, and underscores, as long as you don't start with a number. As you can see, you can declare multiple variables at once by separating the expressions with commas. It's a good idea to do this: at the top of your code, and at the top of every function, declare all the variables you'll need within that file or function (functions: coming soon to a page near you).

But, what do you do if you don't know what the value of that variable should be when you create it? Maybe it's a value that the user is going to give you later on, or something you need to calculate. It's still a good idea to declare the variable, but you don't have to give it a value:

var name;

name = "Jim";

When you declare the variable without giving it a value, the JavaScript engine gives it the default value of undefined. Then, you can give it a new value later.

I know I already said it, but it's important that you understand it: variables are just labels for values. This means they are interchangeable for the most part.

With that out of the way, let's look at the types of data we have in JavaScript.

Types

The first step in learning JavaScript (after we know what a variable is) is to understand two things:

· What basic data types are available, and what they can do

· How the language is actually written (the syntax)

We're going to start by looking at types of data you can use in JavaScript: the parts that will keep your programs running. Then, we'll move on to looking at syntax: that's how to code things so the JavaScript compiler—the thing that reads your code—will understand it.

String

A string is simply the way to handle any kind of text in JavaScript. Whenever you're working with text, you'll be using a string. A string of text must be surrounded by either double or single quotes; there's no difference. Here are some examples:

"Here is some text"

'This text is surrounded by single quotes'

If you want to include a quote character inside your string, then you'll have to escape it. To escape a character inside a string means to precede the character with a backslash. This basically tells the JavaScript interpreter that the character after the slash shouldn't be interpreted normally; it's something special. In this case, the normal interpretation of a quote is to close the string.

Example 2.2

alert( "John says \"What are you doing?\"" ); // John says "What are you doing?"

alert( '"Let\'s go out for lunch."' ); // "Let's go out for lunch."

Notice how, in that last string, I don't have to escape the double quotes, because the string is delimited by single quotes. You only have to escape the quote-type that holds your string.

Numbers

While some programming languages offer different types of numbers, JavaScript has only one. In most cases, you'll simply type the number of your choice.

10

3.14159

JavaScript makes no distinction (at least for you, the coder) between numbers with and without decimals. For extra large or extra small numbers, you can use scientific notation:

Example 2.3

alert( 3.45e5 ); // 345000

alert( 123e-3 ); // 0.123

The first number above represents 3.45 x 105, or 345,000. The second represents 123 x 10-3, or 0.123. Be careful though: JavaScript doesn't accept numbers with more that 17 decimal places. It will cut off any digits after that.

ROCKSTAR TIP

This is a good time to mention that numbers in JavaScript aren't always that reliable. For example, type 0.1 + 0.2 into Firebug. The result is 0.30000000000000004; what? Why does this happen? The reasons are pretty technical, and they're based on the number specification JavaScript uses. Thankfully, as you start out with JavaScript, you won't be doing too much number crunching. However, consider this a general rule of thumb: when adding and subtracting with decimals, multiply them first. After calculating, divide. We haven't discussed operators, yet, but this is the way we'd do it: ( ( 0.1 * 10 ) + ( 0.2 * 10 ) ) / 10 This will come up with the right answer: 0.3. I know this looks painful, but hey, that's JavaScript: at times, terribly frustrating (but mostly fun and cool).

Booleans

There are two Boolean values: true and false. There are many places you'll use Boolean values in your JavaScript code, and when necessary, you'll use these values. However, more often you'll evaluate other expressions for their "truthiness" or "falsiness." We'll see more about how to do this later on in this chapter, when discussing looping and conditionals.

Null and Undefined

Most languages have a value that is the "non-existent" value. By non-existent, I mean that when you try to get a value that doesn't exist (like a variable with no value), you'll get undefined back. There's another value in this strain, and that's null. There isn't usually a need to distinguish between null and undefined; but if you need to "get rid of" the value in a variable, you can set it to null.

Object

What we've looked at so for are considered primitive values; they're the raw pieces that every language has, in some form or another. Now, we move on to reference values. Reference values are different from primitive values (i.e. strings, numbers, booleans, null, and undefined) in that they are passed around your code by reference. I know that's abstract, so we'll come back to this concept when we can put it in context (if you can't wait skip ahead to calling and applying functions).

Objects are one of JavaScript's most powerful features. Think of an object as a wrapper for a bunch of primitive or reference values. Here's an example:

var obj = {

name : "Andrew",

age : 20,

awake : true,

company : {

name : "XYZ Ltd.",

id : 12345

}

};

An object is delimited by curly braces; inside the object, we have a list of key-value pairs. A key-value pair is just what it sounds like: a pair of values, one of which is the key that points to another. If I wanted to get my name out of this object, I'd ask the object for it's name property—that's what we call the value in a key-value pair. Also notice that each pair, except for the last one, ends with a comma; that's important. What's not important is the spacing; I've added some extra spacing here to make our object pretty, but I could have jammed it all on one line, sans any spacing, and it would be the same.

As you can see, any type of value can be a property of an object. I've stuffed a string, a number, a Boolean, and even another object in there. You can access properties in two ways: either the dot notation or the square bracket notation, as showcased below:

Example 2.4

var obj = { name : "Joe", age : 10 };

alert( obj.name ); // "Joe"

alert( obj["age"] ) ; // 10

Creating custom objects like this will be important for your JavaScript applications. It allows you to make your own custom values that aren't built into JavaScript. Need a Person object? No problem. Or what about a tabbed container? JavaScript objects have you covered. We'll come back to custom objects in the next chapter, when we dive ankle-deep into the dirty waters of object-oriented programming.

A final note about objects: you don't need to put all the properties you want them to have in them right away; you can add them later. We'll see more about this later.

Array

Most programming languages have arrays, which are a great way to hold bunches of data. They're very similar to objects, but without the keys.

["Buy milk", "Feed cat", "Pick up dry cleaning", "Deposit Cheque"]

An array is delimited by brackets and each value is separated by a comma. Of course, you aren't limited to strings, as I've used here. Also, you don't have to use only values of the same type in a single array.

["string", 20, false, null, { "id" : 8888 }]

If you've like to access an item from an array, you can use square bracket notation. You would do this to access the first item in the array:

Example 2.5

var arr = ["string", 20, false];

alert( arr[0] ); // "string"

Array item indices are zero-based, which means the first item is 0, the second is 1, and so on.

Date

So far, all the values we've looked at have been literal; this means that we haven't used any "real" code to give the JavaScript interpreter our values; we've just inputted the raw string, number, Boolean, or whatever. The Date value is the first value we'll look at that can't be created that way.

ROCKSTAR TIP

Actually, we can create all the primitive types in a way similar to this, but I'm not going to teach you that, because there's never a good reason to do so.

So, to make a JavaScript Date object, you'll do this:

new Date()

This introduces some new syntax, so let's go over that first. The new keyword simply means we want to create a new object; in this case, that's a date object. Date, in this case, is the name of a function. We'll discuss functions in the next chapter, but they're basically wrappers for related lines of code. You call a function—that means run the code inside it—by placing parentheses after the function name.

What you see above will give you a new date object that holds the date and time you created that object … right down to the millisecond. If you want to create a date object for a specific date or time, you'll have to pass in the right parameters. Parameters? Well, if you want a function to use values outside itself, you have to give them to it. To do so, just put them between those parenthesis that called the function. Don't forget to separate multiple parameters with commas.

There are several parameters you can use to create other dates. You can pass in a string date:

new Date("January 17, 2012")

Or, you can pass a list of parameters, corresponding to the folowing list: year, month, day, hour, minute, second, millisecond. You don't have to add them all; only the ones that matter. It's important to note that the month number is zero-based. This means that to get January, you use the number 0 and to get December, you use 11.

new Date(2009, 3, 20, 17, 30)

This will return April 20, 2009 at 5:30:00.0 PM. Your date object will also include time zone information, based on the settings on your computer.

Semicolons

You may have notices the semicolons popping up here are there in the bits of code we've looked at so far. These are important in JavaScript; they delimit statements. So, when should you use semicolons? Well, the short and easy answer is to use them at the end of each line. The more accurate answer is to use one after each expression statement. Vague, eh? Explaining how all this works is a bit beyond this book. When you're beginning, it's easiest to learn where to put your semicolons by looking at other people's code. As you take your cues from the code snippets you see in this book, these rules will hold true most of the time:

· Any single line that you could put in your Firebug console should have a semicolon at the end.

var someVar = "value"; // semicolon

someFunction("parameter"); // semicolon

· Any statement that includes a block (lines of code between curly braces) should not have semicolons at the end of the lines that open and close the block (the lines that usually end with an opening or closing curly brace).

if (true) { // no semicolon doThis(); // semicolon } // no semicolon

I know this code might not make sense right now, but just keep these semicolon rules in the back of your mind.

Comments

Here's something you'll definitely find useful: you can add comments to your JavaScript code. To make a single-line comment, use two backslashes. You can do this for a whole line, or just part of one:

// This is a useless comment

var x = 10; // x is now equal to 10

If you want multi-line comments, use a backslash and an asterisk; reverse that to end the comment:

/* file: navigtion.js

author: Andrew Burgess

date: July 2, 2011

purpose: provides animation for the site navigation

*/

Make sure you don't abuse comments. Don't litter your files with them, and make the comments you do use worthwhile.

Operators

Well, now that we know what values we can use, and how to store them, let's talk about operators. Operators are used to work with variables and values; often, they'll change variables, or return values that you'll want to assign to variables. Let's take a look at some of the operators we've got in our toolbox.

Arithmetic Operators

These are probably the most often used operators. They're your standard math operators, good friends of most people since about grade 2.

Example 2.6

var four = 2 + 2, //addition operator

hour = 24 - 13, // subtraction operator

seventy = 7 * 10, // multiplication operator

avg_days_per_week = 365 / 52, // division operator

remainder = 31 % 2, // modulus operator

msg = "the time is " + hour + " o'clock"; // addition operator used on strings

console.log(four); // 4

console.log(hour); // 11

console.log(seventy); // 70

console.log(avg_days_per_week); // 7.019230769230769

console.log(remainder); // 1

console.log(msg); // "the time is 11 o'clock"

Besides the obvious ways these operators work, you can see that we're assigning the value of each operation to a variable. Also, notice that we only need to use one var statement, since each variable assignment is separated by commas. Then, notice that + operator is used to concatenate strings. We can even throw a number in there and JavaScript will convert the it to part of the resulting string.

The one operator above that you might not be familiar with is the modulus (%) operator. It returns the remainder or the division of the two numbers. The result for the example above is 1, because 31 / 2 is 15, with remainder 1.

Comparison Operators

Besides acting on values, you'll want to compare them. You'll be familiar with some of these:

Example 2.7

alert( 10 < 5 ); // false

alert( 10 > 5 ); // true

alert( 4 <= 3 ); // false

alert( 4 >= 3 ); // true

It's not hard at all figure which number is greater, or lesser. Besides "less-than" and "greater-than", we've got "less-than-or-equal-to" and "greater-than-or-equal-to." All of these operators return boolean values.

You can use these operators on strings as well:

Example 2.8

alert( "cat" > "dog" ); // false

alert( "bacon" > "chunks" ); // false

alert( "cats" >= "cats" ); // true

alert( "fishing" <= "sleeping" ); // true

alert( "cat" > "CAT" ); // true

How does this work? Well, each letter has a character code, a number that identifies it. It's the numbers that are compared. It's important to note that capital letters don't line up beside their lowercase children. All the capital letters come before the lowercase ones, so "A" < "z" is true.

And it's not just letters that have character codes; every character you can type, including ones you can't (like Shift, Escape, and the others in the modifier gang), has a character code. So a string with numbers or punctuation can be compared this way.

How about just checking to see if two values are equal? Don't make the mistake of doing this:

var a = "cat",

b = "dog";

a = b // WRONG: DOES NOT COMPARE

Look at this for a second; can you see why you can't use = to compare values? That's the assignment operator; you use a single equal-sign to assign a value to variable. To test for equality, you can use three equal-signs (often called the triple-equals operator).

Example 2.9

var a = "cat",

b = "dog";

console.log( a === b ); // false

console.log( a === "cat" ); // true

ROCKSTAR TIP

You might be thinking, "What about two equal-signs? Isn't it dumb to jump from one to three?" Well, there actually is a double-equal operator. Usually, you won't want to use it, because it tries to change the type of your variables. For example, 1 === '1' is false, but 1 == '1' is true, because the double-equal operator will convert the string "1" to the number 1 (We'll talk about converting values soon).

Unary Operators

All the operators we've looked as so far work with two values, one on each side. There are several operators that only work with one value. First off, we've got the incrementing and decrementing operators:

Example 2.10

var i = 0;

i++;

alert(i); // 1

++i;

alert(i); // 2

i--;

alert(i); // 1

--i;

alert(i); // 0

Putting "plus-plus" before or after a number will add one to the number. Predictably, "minus-minus" will subtract one from the number. So, what's the difference between the prefix version and the postfix version? It's this: these operators return a value too, just like the other ones. In this case, they return the value of the number they are incrementing; however, the prefix (that the operator on the front) operators increment the number before returning the value, which the postfix operators return the value, then increment the number. Here's an example:

Example 2.11

var num1 = 1, num2, num3;

num2 = ++num1;

console.log("num1: ", num1); // num1: 2

console.log("num2: ", num2); // num2: 2

num3 = num1++;

console.log("num1: ", num1); // num1: 3

console.log("num3: ", num2); // num3: 2

Another useful unary operator is typeof; this operator will return the type of the given variable:

Example 2.12

alert( typeof 10 ); // "number"

alert( typeof "test" ); // "string"

alert( typeof new Date() ); // "object"

The only catch here is that arrays aren't given this type of array; they are called objects, because—technically—they are. But that's not helpful.

There are a few other unary operators, but we'll see them in a while. Right now, let's talk about our last two groups of operators: extra assignment operators and Boolean operators.

Assignment Operators

We've looked at assigning with the = operator; but there are a few others that I think are taught best by demonstration:

Example 2.13

var num = 10;

num += 5; // same as num = num + 5

alert(num); // 15

num -= 3; // same as num = num - 3

alert(num); // 12

num *= 2; // same as num = num * 2

alert(num); // 24

num /= 6; // same as num = num / 6

alert(num); // 4

num %= 3; // same as num = num % 3

alert(num); // 1

As you can see, these assignment operators are used to perform an operation on a value already in a variable and re-assign the new value to the variable. If you run the above code, you should find that num equals 1 after you run them all.

Boolean Operators

Boolean operators are used to test the trueness or falseness of a value. Every value in JavaScript can be evaluated as a Boolean. Some values are considered false and others are considered true; you'll see how this is important later on in this chapter. For now, know that these values are considered false:

· false

· null

· undefined

· "" (an empty string)

· 0

· Nan (what you get when you try to add, subtract, etc. a number and another non-number value)

Every other value is considered true; keep in mind, this includes the strings "false", "null", and so on.

Now then, back to Boolean operators. The first is the logical NOT; the logical NOT operator converts the given value to the opposite Boolean value.

Example 2.14

var a = "a string";

alert( !a ); // false

alert( !!a ); // true

Since a string with something in it is a true value, using the logical NOT operator will return false. It's just like saying "NOT true." Notice that using NOT twice gives us true; this is a great trick to use when you want to convert any value to its Boolean value.

While the logical NOT is a unary operator, the logical AND and logical OR operators use two values. Look at the syntax, then we'll discuss them:

Example 2.15

var a = true;

var b = false;

alert( a && b ); // false

alert( a || b ); // true

How does this work? And where do these operators do any good? The first one above (&&) is the logical AND operator; it only returns true if both sides of the operator are true. The logical OR (||) returns true as long as just one of the values are true.

So, where is this useful? Well, soon we'll be looking at loops and conditionals, and that's where you'll use this most. In a conditional statement, you'll want to check for certain conditions. If you need two values to be something specific before proceeding, you'll use the logical AND; if only one needs to be true, logical OR will work fine.

I should note that you can use any expression that returns a value; for example:

Example 2.16

var day = 14, year = 2011;

alert( day > 10 || year === 2011 ); // true

alert( day < 20 && year >= 2010 ); // true

You should also know that if the first side of the operator determines the answer, the second side won't be evaluated. For example, in the use of logical OR above, year === 2011 will never be evaluated, because day > 10 returns true, and OR only requires one to be true. On the other hand, if the first half of a logical AND returns false, the second half won't be evaluated, because both sides need to be true for the whole expression to be true.

This fact—that if the first half of the expression determines the final value, the second isn't tested—is used by some of the JavaScript ninjas to shorten their code a bit. Let's say we want to invoke a function (remember, we'll get to functions soon), but we're not sure if the function exists. We could do this:

funcName && funcName();

Remember, to execute the function, we have to have the parentheses, so the first part of this code doesn't execute the function, it just returns the function. If the function exists, this will evaluate to true, and the evaluation will continue to the second part, which executes the function. This avoids the error that would be thrown if we tried to execute a function that doesn't exist (and, yes, we will talk about errors).

Conditional Statements

Several—if not most—of the operators we've just finished looking at are used to determine whether something is true or false. Often, that will be the condition for something further on: if something is true, do this; otherwise, do that. Let's see how this plays out.

If Statements

Pretend for a moment that we're building an app that must output the century a given year is in.

Example 2.17

var year = 2011, msg = "In the ";

if (year > 2000) {

msg += "twenty-first century";

} else {

msg += "twentieth century";

}

console.log(msg); // In the twenty-first century

This is an if-statement. We start with the keyword if. Then, there's the condition inside parentheses. This is where true or false values and operators that return Booleans come into play. They'll determine which statement runs.

We haven't said much about statements yet. In an if-statement, the statement consists of all the lines of code between the opening and closing curly braces. In our example, that's only one line, which appends the century name to the string msg. Then, notice another statement after that one: the else-statement. This will only be executed if the condition before it evaluates to false.

But let's say we're doing something more than a true/false deal. It's not hard to do more:

Example 2.18

var year = 11, msg = "In the ";

if (year > 2000) {

msg += "twenty-first century";

} else if (year > 1900) {

msg += "twentieth century";

} else {

msg += "very distant past.";

}

console.log(msg); // In the very distant past

As you can see, multiple if-statements are no big deal. In place of the else-statement, just put another if-statement. Bump that if right up against the else, add a second condition inside parenthesis, and you're off. Of course, this could go on indefinitely; there's no limit to the number of else if statements you can use.

Switch Statements

However, let's say we're checking something with several options, like the size of coffee a customer wants. We'd have to do something like this:

Example 2.19

var order_size = "medium";

if (order_size === "small") {

alert("small");

} else if (order_size === "medium") {

alert("meduim");

} else if (order_side === "large") {

alert("large");

} else if (order_side === "extra large") {

alert("extra large");

} else {

alert("something else?");

}

Now, I don't know about you, but that last snippet seems like a lot of needless repetition to me. Here's what you can do instead: use a switch statement.

Example 2.20

var order_size = "medium";

switch (order_size) {

case "small":

alert("small");

break;

case "medium":

alert("medium");

break;

case "large":

alert("large");

break;

case "extra large":

alert("extra large");

break;

default:

alert("something else?");

}

Let me introduce you to the switch statement. It's the perfect substitute for long-winded, nested if/else statements. With the switch statement, you only write the expression to evaluate once; it goes in parentheses at the top, right after the keyword switch. Then we open a set of curly braces.

We want to do something based on the evaluation of that expression, so we have any number of cases. The keyword case is followed by the value that we want the expression to match. In this example, the expression order_item is compared to each of the coffee sizes. The compared value is then followed by a colon. Next are the lines of code that will be executed if the expression matches the case; if this is only one line, feel free to put it on the same line as the case "value": part, if you like. It doesn't matter at all, because JavaScript doesn't care about spacing. Don't forget to end your case block with the break; line. This prevents our case statements from falling through; we'll see what this means in a second.

But first, don't forget about the default: piece at the end; yup, you guessed it: it's the equivalent of an else. It executed when we don't match any of the cases.

So, back to falling through: if we didn't include the break; statement, the code for any case statements under the one we match will also be executed. Here's example 2.20, with the break statement removed:

Example 2.21

var order_size = "medium";

switch (order_size) {

case "small":

alert("small");

case "medium":

alert("medium");

case "large":

alert("large");

case "extra large":

alert("extra large");

default:

alert("something else?");

}

Go run this example file: you'll get alerts for "medium," "large," "extra large," and "something else?" At first, this might not make sense; so look at it this way. We can have multiple cases for each code block, meaning that if our condition is one of the cases, the code will execute:

Example 2.22

var order_size = "medium";

switch (order_size) {

case "small":

alert("small");

break;

case "medium":

case "large":

case "extra large":

alert("medium, large, or extra large");

break;

default:

alert("something else?");

}

If we now add some code for each case statement (without any break statements), the same behaviour will take place: the code under each case will run, but it will "fall through" to the next case statement and execute the code there.

You can probably come up with a situation where this would be a neat idea, and save you some coding. However, several of the JavaScript bigwigs consider this a bad practice. What it does is pretty subtle, and it could very easily trip you up when debugging. I'd recommend using a break for every case.

Conditional Operator (Ternary Operator)

There's one more type of conditional statement. Let's say we wanted to do something like this:

var temp = 18, // degrees Celsius

msg;

if (temp > 10) {

msg = "Today was warm";

} else {

msg = "Today was cold";

}

For setting one variable, that seems like a lot of extra code. Well, using the conditional operator, we can shorten it.

ROCKSTAR TIP

You may see the conditional operator called the "ternary operator"; "ternary" just means it takes three values, just like the unary operators take only one. No one gets confused, though, because there's only one ternary operator in JavaScript.

Example 2.23

var temp = 18,

msg = (temp > 10) ? "Today was warm" : "Today was cold";

alert(msg);

It's pretty simple. in parentheses (and really, the parenthesis aren't required, but it improves readability), put your conditional statement, followed by a question mark. Then, we have the value that's used if the condition is true. The value that's returned if the condition is false comes next, after a colon. The conditional operator is great for when your if statements have only two possible outcomes, each of which can be coded in a single line.

Looping Statements

Now that we've got conditional statements down, we're ready to move on to loops. Very often, you'll want to perform the same action several times, each time on a different value. As you might guess, this often goes hand-in-hand with arrays. Let's check out the looping constructs JavaScript gives us.

For Loops

The for loop will often be the first tool you reach for when you need to build a loop. Take a look at the syntax, and then we'll discuss it.

Example 2.24

var names = ["Ringo", "John", "Paul", "George"];

for (var i = 0; i < names.length; i++) {

alert("Say hello to " + names[i]);

}

We begin our for loop with the keyword for; next we have three statements in a set of parentheses. Notice how the statements are separated by semi-colons, just like all good JavaScript statements. The first statement sets any variables we need for the loop; in this case, we're setting only one variable: i = 0 ("i" is short for iterator or index). The second statement is an expression that returns a Boolean value; this is evaluated before the loop is executed. If it evaluates true, the loop will execute; if it evaluates false, the loop will end. In our example, we check to see that i is less than the length of the names array (more on the length property later). The final section performs any action we want to be done after the loop executes; here, we're incrementing i by one. Inside the loop, we can work with the values of the array by using the square bracket notation, passing in an index number—this is where the variable i comes in.

Now, most of the loops you'll see (and probably write, too) will be structured very similarly to this one, even though all three statements in the parenthesis are optional. However, make sure you really understand why this thing works; if you understand what each of these pieces do, your for loops will be more flexible. For example, who says we need to set the variables inside the parentheses?

var i = 0;

for ( ; i < names.length; i++) {

// whatever

}

Notice that even though I've taken the variable declaration outside the loop, we still need to put a semicolon after where the statement would go.

On the other hand, why not set two variables in the first part, and "cache" the value of names.length in the variable len, and use that in the second statement (this really is faster if you're working with a large array).

for (var i = 0, len = names.length; i < len; i++) {

// whatever

}

Notice that I haven't separated the two variable declarations with a semicolon; it has to be one statement, so we separate it with comma.

But then there's the post-loop-actiony part. Why not throw that inside the loop?

for (var i = 0; i < names.length; ){

// whatever

i++;

}

And instead of doing the whole < names.length thing, we could just check to see if the value exists in the array.

var i = 0;

for ( ; names[i] ; ) {

//do something

i++;

}

This is an important point that's relevant to more than just the for loop: if you understand what each piece does, you'll be able wield it more effectively. With this in mind, can you guess why you haven't tried removing the Boolean expression from the for loop? Without that, your loop would loop forever (try it, and crash your browser).

While Loop

Here's a structure that might look a bit like the last for loop we wrote:

Example 2.25

var names = ["Ringo", "John", "Paul", "George"],

i = 0;

while (i < names.length) {

alert("Say hi to " + names[i]);

i++;

}

A while loop is a simpler form of the for loop. Instead of three statements in the parentheses, there's only one: the Boolean expression. If it's true, the while loop will run again. Of course, it starts with the while keyword, followed by the parentheses, and then the block statement. If you're using any variables, you have to initialize them before the loop and increment them within the loop. Depending on your task, a while loop can be more elegant than a for loop. What I've shown above is using a while loop for iteration; that's usually better off left to a for loop. A while loop, semantically, should be used while something is true:

Example 2.26

var not_home = true,

miles_driven = 0;

while (not_home) {

miles_driven += 1 // drive another mile

if (miles_driven === 10) {

not_home = false;

}

}

alert(miles_driven);

For Loop, Revisited

There's another form of for loop that you should now about, usually called a for-in loop. It's used for looping over objects. Check it out:

Example 2.27

var person = {

name : "Jules Verne",

job : "Author",

year_of_birth: 1828,

year_of_death: 1905

},

prop;

for (prop in person) {

alert("His " + prop + " is " + person[prop]);

}

As you can see, a for-in loop is much simpler than the regular for loop. Instead of the three statements, we only put one in the parentheses: the name of the iterator variable, the keyword in, and the object we're going over. As expected, this will execute the inside of the block for each item or property in the array or object, respectively. There's a caveat that you must be aware of when using the for-in loop with objects, but we'll discuss this more in the next chapter.

Summary

You should be warming into our topic by now. We've covered the different types available in JavaScript, most of the operators, and how to use conditions and loops. In the next chapter, we're going talk about one of the most important features of JavaScript: functions.