The JavaScript if...else statement
The if...else statement runs one block of code when a condition is true and an optional else block when it's false. if (age >= 18) { ... } else { ... }. Chain extra conditions with else if. It's the most fundamental way to make decisions in JavaScript.
Overview
if is how a program makes choices. You give it a condition in parentheses, and if that condition is truthy the block runs; otherwise it's skipped. Add an else for the false case, and chain else if for several mutually exclusive paths. This is the backbone of nearly every program.
The condition doesn't have to be a literal true/false — JavaScript evaluates it for truthiness. Most values are truthy; the falsy ones are a short list worth memorizing: false, 0, "", null, undefined and NaN. So if (name) runs when name is a non-empty string, which is a common, readable shorthand.
For comparisons inside the condition, prefer the strict === over loose == to avoid surprising type coercion. When you're choosing between a value and an alternative, a ternary is often tidier than a full if...else. And when you're checking one value against many fixed options, a switch can read more cleanly than a long else if chain.
Syntax
if (condition) {
// runs when condition is truthy
} else if (otherCondition) {
// runs when the first is false and this is truthy
} else {
// runs when none above were true
}
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const hour = new Date().getHours();
let greeting;
if (hour < 12) {
greeting = 'Good morning';
} else if (hour < 18) {
greeting = 'Good afternoon';
} else {
greeting = 'Good evening';
}
document.getElementById('out').textContent = greeting + '!';
</script>
Best practices
- Use strict === in conditions to avoid loose-equality type coercion bugs.
- Lean on truthiness for simple checks (
if (value)), but know the falsy list:false, 0, "", null, undefined, NaN. - Reach for a ternary when choosing between two values, and a switch for many fixed cases.
- Keep blocks braced even for one line — it prevents bugs when you add a second statement later.
Frequently asked questions
How does an if statement work in JavaScript?
else block when it's false.What values are falsy in JavaScript?
false, 0, "" (empty string), null, undefined and NaN. Everything else is truthy.When should I use a ternary instead of if...else?
const x = ok ? a : b is cleaner than a full if...else.Should I use == or === in conditions?
0 == "" being true.