3D Game Programming

(C. Jardin) #1

Running Code Only If Something Is True


Sometimes we want to skip over code entirely. For these times, we use the if
keyword. Just like while, the if keyword does something with a block of code:

vargame ="started";
// More code here that might change the variable "game"
// to something else...

if(game =="over") {
console.log("Game Over!!!");
}

The if keyword lets us write JavaScript code that runs only if some condition
is true. In this case, we check if game is equal to the string over, using the
double equals (==) operator to do so.

We can also extend an if statement with else if and else. Consider the following
code, which we’ll use to turn and move a raft in Chapter 20, Project: River
Rafting, on page 185:

document.addEventListener("keydown",function(event) {
varcode = event.keyCode;
❶ if(code == 32) pushRaft(); // space
❷ else if(code == 37) rotateRaft(-1);// left
❸ else if(code == 39) rotateRaft(1); // right
❹ else{// Something else
console.log(code);
}
});

We’ll talk more about the code in the project chapters, but we see that


❶if the code is a space bar code, then we push the raft forward


❷otherwise, if the code is for the left arrow key, then we turn the raft to the
left

❸otherwise, if the code is for the right arrow key, then we turn to the right


❹otherwise, some strange key is pressed and we just log the code to the
JavaScript console

Don’t Overuse Ifs

If, else if, and else are very powerful, but can be used too much. We’ll
talk about better approaches in some of the project chapters.

Chapter 7. A Closer Look at JavaScript Fundamentals • 76


Prepared exclusively for Michael Powell report erratum • discuss

Free download pdf