JavaScript If / Else If / Else Control


Example

In its most simple form, an if condition can be used like this:

var i = 0;

if (i < 1) {
    console.log("i is smaller than 1");
}

The condition i < 1 is evaluated, and if it evaluates to true the block that follows is executed. If it evaluates to false, the block is skipped.

An if condition can be expanded with an else block. The condition is checked once as above, and if it evaluates to false a secondary block will be executed (which would be skipped if the condition were true). An example:

if (i < 1) {
    console.log("i is smaller than 1");
} else {
    console.log("i was not smaller than 1");
}

Supposing the else block contains nothing but another if block (with optionally an else block) like this:

if (i < 1) {
    console.log("i is smaller than 1");
} else {
    if (i < 2) {
        console.log("i is smaller than 2");
    } else {
        console.log("none of the previous conditions was true");
    }
}

Then there is also a different way to write this which reduces nesting:

if (i < 1) {
    console.log("i is smaller than 1");
} else if (i < 2) {
    console.log("i is smaller than 2");
} else {
    console.log("none of the previous conditions was true");
}

Some important footnotes about the above examples:

  • If any one condition evaluated to true, no other condition in that chain of blocks will be evaluated, and all corresponding blocks (including the else block) will not be executed.

  • The number of else if parts is practically unlimited. The last example above only contains one, but you can have as many as you like.

  • The condition inside an if statement can be anything that can be coerced to a boolean value, see the topic on boolean logic for more details;

  • The if-else-if ladder exits at the first success. That is, in the example above, if the value of i is 0.5 then the first branch is executed. If the conditions overlap, the first criteria occurring in the flow of execution is executed. The other condition, which could also be true is ignored.

  • If you have only one statement, the braces around that statement are technically optional, e.g this is fine:

    if (i < 1) console.log("i is smaller than 1");
    

    And this will work as well:

    if (i < 1) 
        console.log("i is smaller than 1");
    

    If you want to execute multiple statements inside an if block, then the curly braces around them are mandatory. Only using indentation isn't enough. For example, the following code:

    if (i < 1) 
        console.log("i is smaller than 1");
        console.log("this will run REGARDLESS of the condition"); // Warning, see text!
    

    is equivalent to:

    if (i < 1) {
        console.log("i is smaller than 1");
    }
    console.log("this will run REGARDLESS of the condition");