Conditionals
Overview
Programs need to make decisions: show an error if a form field is empty, offer a discount if the basket is big enough, say good morning or good evening. An if statement runs a block of code only when its condition is true.
const temperature = 31;
if (temperature > 30) {
console.log('It’s hot today.');
}The part in brackets is the condition. It can be any expression; JavaScript evaluates it and, if the result is truthy, runs the block in curly braces. Otherwise the block is skipped and the program carries on after it.
else
Add an else block to run code when the condition is false. Exactly one of the two blocks runs:
const age = 16;
if (age >= 18) {
console.log('You can vote.');
} else {
console.log(`You can vote in ${18 - age} years.`);
}else if
For more than two outcomes, chain conditions with else if:
const hour = 14;
if (hour < 12) {
console.log('Good morning');
} else if (hour < 18) {
console.log('Good afternoon');
} else {
console.log('Good evening');
}JavaScript checks each condition in order and runs the first block that matches. The rest are skipped — even if their conditions would also be true.
Order matters
Because the first match wins, put the most specific conditions first. This version has a bug:
if (score >= 50) {
grade = 'C';
} else if (score >= 90) {
grade = 'A'; // never reached — 95 already matched >= 50
}Checking from highest to lowest fixes it.
Combining conditions
Use logical operators to build richer conditions:
if (age >= 18 && hasTicket) {
console.log('Welcome in!');
}
if (day === 'Sat' || day === 'Sun') {
console.log('Weekend!');
}
if (!isLoggedIn) {
showLoginButton();
}When a condition gets long, give it a name. The if then reads like a sentence:
const isWeekend = day === 'Sat' || day === 'Sun';
const canBook = isMember && seatsLeft > 0 && !isWeekend;
if (canBook) {
book();
}To check a value against a list, includes is shorter than many ||:
if (['Sat', 'Sun'].includes(day)) { /* weekend */ }Truthy and falsy conditions
The condition doesn’t have to be a boolean. These values count as false: false, 0, '', null, undefined and NaN. Everything else counts as true.
const name = '';
if (!name) {
console.log('Please enter your name.');
}
const items = [];
if (items.length) {
console.log('You have items'); // skipped: length is 0, which is falsy
}Be careful when 0 is valid.
if (quantity)is false for0, which might be a perfectly good quantity. Write exactly what you mean:if (quantity !== undefined)orif (quantity > 0).
Nesting
Blocks can contain other if statements:
if (user) {
if (user.isAdmin) {
showAdminPanel();
} else {
showDashboard();
}
}A little nesting is fine, but deep nesting — sometimes called the “arrow” or “pyramid” shape — makes code hard to follow. The next technique flattens it.
Early returns
Inside functions, returning as soon as you know the answer avoids deep nesting. These checks at the top of a function are called guard clauses:
// Nested
function canEnroll(user) {
if (user) {
if (user.verified) {
return user.age >= 13;
}
}
return false;
}
// Flat, with guard clauses
function canEnroll(user) {
if (!user) return false;
if (!user.verified) return false;
return user.age >= 13;
}Both do the same thing, but in the second version each rule is on its own line, and the “happy path” is at the bottom with no indentation.
Choosing a value: the ternary
When you only need to pick between two values, the ternary operator is shorter than an if…else:
// if…else
let message;
if (isMember) {
message = 'Welcome back';
} else {
message = 'Sign up today';
}
// ternary
const message = isMember ? 'Welcome back' : 'Sign up today';Use if when you need to do things (run several statements); use the ternary when you need to choose a value.
Braces
If a block has only one statement, the braces are optional:
if (isDone) console.log('Finished');That’s fine for one-line guard clauses, but always use braces for anything longer. Without them, only the first statement belongs to the if, and adding a second line later is a classic bug:
if (isDone)
console.log('Finished');
celebrate(); // always runs — it's not part of the if!Keep conditions readable. If a condition gets long, give it a name:
const isWeekend = day === 'Sat' || day === 'Sun';
Grade a score
Write grade(score) that returns 'A' for 90+, 'B' for 75+, 'C' for 50+, and 'Try again' otherwise. Return 'Invalid' if the score is below 0 or above 100.
function grade(score) {
// your code here
}
grade(95); // 'A'
grade(60); // 'C'
grade(120); // 'Invalid'function grade(score) {
if (score < 0 || score > 100) return 'Invalid';
if (score >= 90) return 'A';
if (score >= 75) return 'B';
if (score >= 50) return 'C';
return 'Try again';
}Summary
ifruns a block only when its condition is truthy.- Chain checks with
else if; the first match wins, so order matters. - Combine conditions with
&&and||; name long conditions with aconst. - Returning early (guard clauses) keeps functions flat and readable.
- Use the ternary operator when you just need to choose between two values.