JavaScript Making Decisions

Nesting If Statements

By using if statements with both comparison and logical operators we can set up code that will be run if a specific combination of conditions is met. We don’t always want to test the entire condition in order to run one set of statements if the entire test is true and another if it is false. What about if we want to be able to choose between several different statements depending on which particular combination of conditions is true.

Just as we can use an else with an if statement in order to avoid having to test the same condition twice we can also nest if statements inside one another in order to minimize the number of times that various tests need to be performed.

Suppose for example that we have three values that we want to compare and different results that we want to set depending on which of them are equal. The following example shows how we can nest if statements to test for this.

var answer;
if (a == b) {
  if (a == c) {
    answer = "all are equal";
  } else {
    answer = "a and b are equal";
  }
} else {
  if (a == c) {
    answer = "a and c are equal";
  } else {
    if (b == c) {
      answer = "b and c are equal";
    } else {
      answer = "all are different";
    }
  }
}

There are several things to notice with how this is coded. First, I have created the variable to hold the result first before the if statement. If I hadn’t done that then I would have needed to include the var on the front of all of the assignment statements in order to make answer a local rather than a global variable.

Secondly I have indented each nested if statement. This allows us to track more easily how many nested levels of if statements that there are. It also makes it clearer that we have closed the right number of blocks of code to complete all of the if statements that we have opened. You may find that it is easier to put the braces there first for each if statement, before you start writing the code that belongs inside that block.

We can simplify one section of this code slightly in order to avoid having to nest the if statements quite as much. Where an entire else block is made up of a single if statement we can omit the braces around that block and move the if condition itself up onto the same line as the else as shown here.

var answer;
if (a == b) {
  if (a == c) {
    answer = “all are equal”;
  } else {
    answer = “a and b are equal”;
  }
} else if (a == c) {
  answer = “a and c are equal”;
} else if (b == c) {
  answer = “b and c are equal”;
} else {
  answer = “all are different”;
}

go to previous section go to next section 

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate