ChApter 1 ■ JAvASCrIpt You Need to KNow
Andrew
Grant
21
Remember the use of the associative array syntax that we discussed earlier? myObject[prop] is a good example of
where this technique is needed.
Control Flow
Generally speaking, JavaScript is read by the browser line by line, unless you tell it otherwise, using, for example, a
loop or branch statement. Looping is the ability to repeat the execution of a block of code a number of times; whereas
branching is the ability to jump to one block of code or potentially some other block of code.
Loops
Let’s start off with loops. Arguably the most common loop structure in JavaScript is the for loop. The for loop can
seem complicated at first, but it’s not difficult to use, once you understand what it is composed of.
There are four key parts to a for loop:
- Counter variable. This is something that is created and usually used only in the for loop.
Its main task is to keep count of how many times the loop has been entered. - Conditional logic. This is where the decision is made on whether or not the for loop
should continue. - Counter variable. This is usually incremented, or otherwise altered, after every loop.
- Code block. This is the actual block of code that is executed at each pass through the loop.
With these explanations in mind, let’s examine Listing 1-22, which shows the for loop in action. I hope you will
be able to read through this and relate each part back to the preceding points.
Listing 1-22. The for Loop in Action
<!DOCTYPE html>