JavaScript-Web-Final

Page 40

40

The Basics

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


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.