The if statement is composed of the if keyword followed by a parenthesized expression and then an additional statement:
if (ConditionExpression) Statement
ConditionExpression can be of limitless complexity as long as it is truly an expression:
if (true) {}
if (1 || 2 || 3) {}
if ([1, 2, 3].filter(n => n > 2).length > 0) {}
The statement following the parenthesized expression can be a single-line statement or a block and designates the code that should be run if the ConditionExpression evaluates to a truthy value:
// These are equivalent
if (true) { doBaz(); }
if (true) doBaz();
The value you pass as ConditionExpression is compared to a Boolean to determine its truthiness. We've already been aptly introduced to the concepts of truthiness and falsiness in Chapter 6, Primitive and Built-In Types, but just in case you're rusty: there are only seven falsy values in JavaScript, and as such, only seven possible values that you can pass to an if statement that won't satisfy it:
if (false) {}
if (null) {}
if (undefined) {}
if (0n) {}
if (0) {}
if ('') {}
if (NaN) {}
When an if statement is not satisfied, it will run an optional else statement, which you may specify immediately following your if statement. Just as with if, you may use a block here as well:
if (isLegalDrinkingAge) drink(); else leave();
// Equivalent, with Blocks:
if (isLegalDrinkingAge) {
drink();
} else {
leave();
}
You can effectively chain together if/else statements as follows:
if (number > 5) {
// For numbers larger than five
} else if (number < 3) {
// For numbers less than three
} else {
// For everything else
}
Syntactically, it's important to understand that this isn't a construct of its own (there is no such thing as an if/else/if/else construct); it is merely a regular if statement, followed by an else statement that itself contains its own if/else duo. Therefore, it is more accurate, perhaps, to see it as follows:
if (number > 5) {
// For numbers larger than five
} else {
if (number < 3) {
// For numbers less than three
} else {
// For everything else
}
}
An if statement is best suited for when there are one or two possible outcomes of a condition. If there are more possible outcomes, then you may be better off using a switch statement. Long if/else chains can get unwieldy. See the Handling cyclomatic complexity section later in this chapter to explore other novel ways of handling complex conditional logic.