if-else

suggest change

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 (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");

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents