Java Reference
In-Depth Information
Logic
In this section we will begin to look at logical conditions that allow you to control the flow
of a program.
if
Statements
An
if
looks like the following:
if (condition) {
code to run if condition is true
}
The code inside the block will only run if the condition is true. If the condition is not a
Boolean value, it will be converted to a Boolean, depending on whether or not it is truthy or
falsy (see
Chapter 2
).
Here is an example that will only display the alert message if the value of the
age
variable
is less than 18:
var age = 23;
if (age<18) {
alert("Sorry, you are not old enough to play this game");
}
Try changing the value of the
age
variable to a value below 18 as it does in this code, and
the alert box will show as in
Figure 3.7
:
var age = 12;
if (age < 18) {
alert("Sorry, you are not old enough to play this game");
}
