Forks in the Code
The if statement is the foundation of any algorithm. It executes a block of code if the condition in the parentheses is true.
1. The Basics
if (age >= 18) {
alert('Access granted');
} else {
alert('You are too young');
}
2. What is considered false (Falsy)?
JS automatically coerces the result in the parentheses to a boolean type. Exactly 6 values in JS turn into false:
false0(and-0)""(empty string)nullundefinedNaN
All other values (including empty objects {} and arrays []) are true.
Important
Be careful with a string containing a single space " ". It is NOT empty, so in an if statement it will become true.
Tip
Use else if when there are more than two conditions. But if there are too many, it might be worth looking at switch.