if-else
suggest changeIn its most simple form, an if condition can be used like this:
const i = 0;
if (i < 1) {
console.log("i is smaller than 1");
}
The condition i < 1 is evaluated. If it is truthy, the following block runs. If it is falsy, 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 theelseblock) will not be executed. - The number of
else ifparts is practically unlimited. The last example above only contains one, but you can have as many as you like. - The condition inside an
ifstatement can be any value. It is coerced to a Boolean. See logic operators with non-Boolean values. - The
if-else-ifladder exits at the first success. That is, in the example above, if the value ofiis 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 the branch is a single statement, the braces are optional. This braced form is fine:
if (i < 1) {
console.log("i is smaller than 1");
}
This form works as well, because the one statement is the if body:
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");