3D Game Programming

(C. Jardin) #1
Code in ICE, Check in the Console
The code in the rest of this chapter is too large for the JavaScript
console, so add it in ICE after the START CODING line. Be sure to keep
the JavaScript console open—even though we’re not typing code
in there, we’ll still use it to show messages.

While


If a section of code, which we call a block, starts with while, then the block is
run again and again until something changes. The something that needs to
change goes in parentheses after the while keyword:

vari = 0;
while(i < 5) {
console.log("i is now: "+ i);
i = i + 1;
}

If you try this and check in the JavaScript console, you’ll see something like
the following:

i is now: 0
i is now: 1
i is now: 2
i is now: 3
i is now: 4

Each time through the code block, we log the variable i to the JavaScript
console. We also do a little math. We add 1 to the old value of i. Then the
computer will run the while block again—as long as i is less than 5 (that <
symbol means less than). As soon as i is equal to 5 , the computer stops
rerunning the while block and moves on to the next lines.

Try This Yourself

What happens if you run the following?


vari = 0;
while(i < 5) {
console.log("Chris is awesome!!!!");
i = i + 1;
}

Be sure to try your own name!


report erratum • discuss

Repeating and Skipping Code with while and if • 75


Prepared exclusively for Michael Powell

Free download pdf