Conditionals
Syntax for running different code based on a condition.
if statements
let age = 18;
if (age >= 18) {
console.log("You are an adult");
} else if (age >= 13) {
console.log("You are a teenager");
} else {
console.log("You are a child");
}
truthy and falsy
The condition of an if can be a value other than true / false. In that case, JavaScript automatically converts the value to a boolean. The values treated as false (falsy) are the following 6 representative ones, and everything else is true (truthy).
// Falsy values (the 6 representative ones)
if (false) {} // false
if (0) {} // the number 0
if ("") {} // the empty string
if (null) {} // null
if (undefined) {} // undefined
if (NaN) {} // NaN
// Everything else is truthy
if ("0") {} // the string "0" is truthy (because it has content)
if ([]) {} // an empty array is also truthy (arrays are covered in a later chapter)
if ({}) {} // an empty object is also truthy
It might feel surprising that if ("0") is true. Because any string with content is truthy, "0" and "false" are also treated as true. Be aware that the number 0 and the string "0" are different things. Strictly speaking, -0 and the BigInt 0n are also falsy, but in everyday use the 6 above are enough to keep in mind.
Logical operators and the nullish coalescing operator
Logical operators have a mechanism called "short-circuit evaluation" and are often used to specify default values.
// && (AND): if the left is truthy, return the right
console.log(true && "Value"); // Value
// || (OR): if the left is falsy, return the right (often used for default values)
const name = "" || "Guest";
console.log(name); // Guest
// ?? (nullish coalescing): return the right only when the left is null or undefined
const count = 0 ?? 10;
console.log(count); // 0 (0 is not null/undefined, so it's left as is)
const value = null ?? 10;
console.log(value); // 10
Because || also rejects 0 and "" as falsy, it behaves unexpectedly in situations where you "want to treat 0 as a valid value." ?? (ES2020) returns the right side only when the value is null or undefined, so it suits the use case of "using a default only when the value is not set."
The ternary operator
A conditional operator that lets you write if-else more briefly.
// condition ? value if true : value if false
const score = 85;
const result = score >= 60 ? "Pass" : "Fail";
console.log(result); // Pass
switch statements
Used when handling multiple branches.
let fruit = "Apple";
switch (fruit) {
case "Apple":
console.log("Apples are red");
break;
case "Banana":
console.log("Bananas are yellow");
break;
case "Orange":
console.log("Oranges are orange");
break;
default:
console.log("I don't know the color of that fruit");
}
If you forget break, the case below it will also run (fall-through). There are patterns that use this intentionally, but normally write break at the end of each case.
What to read next
- Loops — Repeat the same processing according to a condition