HTML and CSS Reference
In-Depth Information
Conditional statements such as the if statement can be nested, like in the following
var userAge = 10, gender = 'M';
var minimumAge = 11;
if (userAge > minimumAge) {
if (gender == 'M') {
//do logic for above age male
else {
//do logic for above age female.
} else if (gender == 'M') {
//do logic for underage male
} else {
//do logic for underage female.
In this example, the logic tests whether a user is older than a specified age. If the user is
over the specified age, the logic in the true branch runs. At that point, another if statement
evaluates the user's gender. If the user's age is younger than the required minimum, the false
branch is processed. Here an else if statement performs additional conditional processing on
the false branch based on the gender. Again, the code processes a specific branch depending
on whether the user is male or female.
You aren't limited in how deeply you can nest if statements, but nesting them too deeply
can make the code quite messy and difficult to read.
The following example examines the background color of an element and processes
specific behavior based on the color:
var canvas = document.getElementById("canvas1");
if ( == 'green') {
} else if ( == 'yellow') {
alert('slow down/safely stop');
} else if ( == 'red') {
This code retrieves a reference to a page element called canvas1 and then evaluates that
element's background color to determine an appropriate action to take. In some places,
whether by law or preference, yellow sometimes means “proceed faster.” In that case, the
code could be adapted to use the OR logical operator:
var canvas = document.getElementById("canvas1");
if ( == 'green' || == 'yellow')
} else if ( == 'red') {
Search WWH ::

Custom Search