How to Nest Your JavaScript If Statements for HTML5 and CSS3 Programming

There are a few variations of the if structure you'll sometimes run across in JavaScript when programming your HTML5 pages. One variation is the nestedif statement. This simply means you can put if statements inside each other for more complex options. For example, look at the following code:

This code looks complicated, but it really isn't. It simply takes in a temperature and looks for a range of values. Here's what's happening:

Get a temperature value from the user.

Ask the user for a temperature. A simple prompt statement is used here, but you could also grab the value from a form field.

Convert the temperature to a numeric type.

Recall that computers are fussy about data types, and sometimes you need to nudge a variable to the right type. The parseInt() function forces any value into an integer, which is perfect for our needs.

Use an if statement to chop the possibilities in half.

The outer (most encompassing) if statement separates all the cooler temperatures from the warmer ones.

Use an inner if statement to clarify more if needed.

Within the cool (less than 60 degree) temperatures, you might want to know if it's cold or below freezing, so place a second condition to determine the temperatures.

The upper bound is determined by the outer if statement.

The first else clause in the code is triggered when the temperature is between 32 and 60 degrees because it's inside two if statements: temp<60 is true, and temp<32 is false, so the temperature is between 32 and 60 degrees.

Indentation and comments are not optional.

As the code becomes more complex, indentation and comment characters become more critical. Make sure your indentation accurately reflects the beginning and end of each if statement, and the code is clearly commented so you know what will happen (or what you expect will happen — the truth may be different).

You can nest as deeply as you wish.

As you can see in this structure, there are three different possibilities for temperatures higher than 60 degrees. Simply add more if statements to get the behavior you wish.

Test your code.

When you build this kind of structure, you need to run your program several times to ensure it does what you expect.