if else statement - if-else statement - javascript - javascript if else statement

Controlling Program Flow with Javascript If Else Statements

The Javascript if else statement, also known as an if statement, has been a core feature of the language for decades. You can think of it as a way to insert cause and effect into your programming, creating a logical flow of actions.

This article describes what if else statements are and goes over some best practices for using them well in Javascript programs.

Overview of Javascript If-Else Statements

Javascript if else statements use reserved words and specific structures to control what happens in a program when a condition is met. An if else statement always starts with the reserved word “if” followed by a condition that must be met.

The simplest type of if else statement has no “else” at all — it describes what happens when a condition is met without providing any alternatives. In Javascript, the general structure for the statement looks like this:

if (condition) {
   ... instructions ...
}

Use the reserved word “else” to define what happens if a condition is not met. Always remember to surround both sets of instructions, whether a condition is met or not, with curly braces to create a code block:

if (condition) {
   ... instructions if met ...
} else {
   ... instructions if not met ...
}

You can also build an if else statement that contains multiple separate conditions a program could meet. In this case, use the reserved phrase “else if” to create separate conditions.

if (condition1) {
   ... instructions if met ...
} else if (condition2) {
   ... instructions if met ...
}

If none of the conditions are met, you can use the reserved word “else” by itself as a default to describe that scenario. It’s important to always put the “else” after all the other conditions — an “else” before an “else if” is a syntax error in Javascript.

//
// CORRECT (else as default after all other conditions)
//
if (condition1) {
   ... instructions if met ...
} else if (condition2) {
   ... instructions if met ...
} else {
   ... instructions if no conditions were met ...
}

//
// INCORRECT (else as default before other conditions)
//
if (condition1) {
   ... instructions if met …
} else {
   ... instructions if no conditions were met ...
} else if (condition2) {
   ... instructions if met ...
}

Advanced programmers can place if statements inside one another with a technique called “nesting”, creating a complex hierarchy of logic. You can use any type of if statement inside any other as many times as you want.

if (condition1) {
   ... instructions if condition1 met ...
   if (condition1B) {
      ... instructions if condition1B met ...
   }
} else if (condition2) {
   ... instructions if condition2 met …
   if (condition2B) {
      ... instructions if condition2B met ...
   } else {
      ... instructions if condition2B not met ...
   }
} else {
   ... instructions if no conditions were met ...
}

Good Practices for Javascript If Else Statements

Chaining

“Chaining” is creating a series of conditions in a single if statement where each condition is tested in order using the reserved phrase “else if.” When a condition is met within the if statement, the rest of the conditions in that statement are ignored:

if (condition1) {
   ... instructions if met ...
} else if (condition2) {
   ... instructions if met …
   ... condition3 and default behavior in “else” not tested
} else if (condition3) {
   ... instructions if met …
   ... default behavior in “else” not tested
} else {
   ... instructions if no conditions were met ...
}

This is an important way to create logical flows, but it can become difficult to follow when many conditions are involved. The longer your chain is, the more confusing it can be, as in this example:

if (condition1) {
   ... instructions if met ...
} else if (condition2) {
   ... instructions if met …
} else if (condition3) {
   ... instructions if met …
} else if (condition4) {
   ... instructions if met …
} else if (condition5) {
   ... instructions if met ...
} else {
   ... instructions if no conditions were met ...
}

You should keep the number of conditions in a single chained if statement as small as possible so it’s always clear which logical path your code takes. Adding comments above each condition can make paths clearer.

Nesting

The act of placing if statements inside each other is called nesting. Nesting creates logical flows that combine conditions from multiple if statements, but too much nesting can cause confusion.

In this example, three different nested if statements handle combinations of six different conditions. The deeper you go into the nested statements, the harder it is to know which conditions were met to get there.

if (condition1) {
   ... instructions if condition1 met …
   if (condition3) {
      ... instructions if condition3 met …
      if (condition5) {
         ... instructions if condition5 met ...
      } else if (condition6) {
         ... instructions if condition6 met ...
      }
   } else if (condition4) {
      ... instructions if condition4 met ...
   }
} else if (condition2) {
   ... instructions if condition2 met ...
}

Can you tell at a glance how the code gets to the instructions under condition 6? If you answered “no,” you’re not alone; this deeply nested example is hard to unravel.

When each condition contains many lines of code instructions, splitting the nested if statements into separate functions is the best way to clarify logical flow. Doing this usually creates more lines of code, but you can step through functions to understand what is happening in the program, especially if the functions have descriptive names.

//
// Functions
//

function doCondition1() {
   ... instructions …
   if (condition3) {
      doCondition3();
   } else if (condition4) {
      doCondition4();
   }
}

function doCondition2() {
   ... instructions ...
}

function doCondition3() {
   ... instructions ...
   if (condition5) {
      doCondition5();
   } else if (condition6) {
      doCondition6();
   }
}

function doCondition4() {
   ... instructions ...
}

function doCondition5() {
   ... instructions ...
}

function doCondition6() {
   ... instructions ...
}

//
// Original If Statement
//

if (condition1) {
   doCondition1();
} else if (condition2) {
   doCondition2();
}

Don’t forget that you have to declare the functions before you use them. If you declare functions after the if statement, Javascript won’t understand the functions’ names when it’s reading the if statement.

By using 6 functions, this code makes it clear that there are 6 different conditions that could be met, but that not all conditions must be met to reach condition 6. Stepping through the code reveals the following steps to get to condition 6.

  1. Meet condition 1
  2. Meet condition 3
  3. Do not meet condition 5
  4. Meet condition 6

Layout and Consistency

Since if statement chaining and nesting can become complex, it’s helpful to have a consistent way of writing if statements. This article’s examples place the reserved words of an if statement — that is, “if”, “else” or “else if” — on their own lines with code blocks on subsequent lines.

Some developers align code blocks and reserved words differently in if statements, and there is no single “proper” way. All of the following examples are valid if statements.

if (condition) {
   ... instructions ...
}

if (condition) 
{
   ... instructions ...
}

if (
      condition
   ) {
   ... instructions ...
}

if (condition1) { ... instructions ... }

Whatever statement layout you use, remember that readability is important. All code needs maintenance sometimes, and understanding what code does, months or years later, can save you a lot of time.

Javascript If Else Statements and Ternary Operators

The Javascript if-else statement controls how a program makes decisions but it can’t return values or save information into variables directly. Usually, you need to declare variables outside of the statement, assign them inside the statement, then do something with the variables later:

let x = 1;
let y = 2;
if (y = 2) {
    X = 5;
}
console.log(x);

The ternary operator in Javascript mimics if else statements, but allows you to return a value directly. It is usually written on one line like this:

let myVariable = (condition) ? value if true : value if false

The 6 lines of code needed to assign a variable in the previous example can be rewritten as 3 lines with a ternary operator:

let y = 2;
let x = (y == 2) ? 5 : 1;
console.log(x);

Ternary operators have a similar structure to if statements in that they have conditions in parentheses that must be met. They are different from if statements in that they can only hold values, not complex instructions.

Most if statements cannot be replaced by ternary operators, but simple if statements may be more understandable when written with a ternary operator, especially if they’re only setting the value of a variable. Always remember that ternary operators require both a true and false value.

Conclusion

If else statements are an important part of a Javascript developer’s toolbox, but they add complexity to code, so you should always follow best practices when using them. Whether you use simple binary choices or complex chains with nested statements, there is no limit to the logic you can implement with if statements.

Enroll in our Intro to Programming Nanodegree program today to learn more about Javascript if-else statements and other programming concepts.

Start Learning

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni