Chapter 12. Conditions: choosing code to run
This chapter covers
- Comparing values with comparison operators
- Checking conditions that are true or false
- The if statement—running code only if a condition is met
- The else clause—running code when a condition is not met
- Making sure user input won’t break your code
- Generating random numbers with Math.random()
So far, all of your code follows a single path. When you call a function, every statement in the function body is executed. You’ve managed to get a lot done and covered quite a few core ideas in JavaScript but your programs have lacked flexibility; they haven’t been able to decide whether or not to execute blocks of code.
In this chapter you learn how to run code only when specified conditions are met. Suddenly, your programs can branch, providing options, flexibility, and richness. You can increase a player’s score if they splat a kumquat, move to a new location if the user specifies a valid direction, or post a tweet if it’s less than 141 characters long.
If you want to find out how your programs can make decisions, read on, else, ... well, read on anyway. You really need to know this stuff!
To start, create a simple program that asks the user to guess a secret number. If they guess correctly, the program says, “Well done!” An interaction at the console might look like this: