if...else
Executes a block of code conditionally, with optional else branches.
Syntax
if (condition) {
// ...
} else if (other) {
// ...
} else {
// ...
}
Examples
const n = 7;
if (n % 2 === 0) {
console.log("even");
} else {
console.log("odd");
}
Output
odd
const score = 82;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else {
console.log("C");
}
Output
B
const value = 0;
if (value) {
console.log("truthy");
} else {
console.log("falsy");
}
Output
falsy
Notes
- The condition is coerced to a boolean; falsy values are `false`, `0`,
`-0`, `0n`, `""`, `null`, `undefined`, and `NaN`.
- Braces are optional for single statements but recommended for clarity.
- For multi-way branching on a single value, consider `switch` or the
ternary operator.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |