Conditions
if...else
Runs different code depending on a condition.
Why it exists
A program without conditions would do the same for everyone: show a "Sign in" button to someone already signed in, let you pay for an empty cart. if lets code react to the situation: if the cart is empty, show a hint; otherwise show the pay button. Almost all of an app's "logic" is conditions.
Where it's used
- Show different things: "Sign in" for a guest, an avatar for a signed-in user.
- Check input: if a field is empty, show an error and don't submit the form.
- Early exit from a function:
if (!user) return null;. - Branching on options: plan, role, order status.
Syntax
if (condition) {
// when true
} else {
// when false
}Examples
function sign(x) {
if (x > 0) return "plus";
else if (x < 0) return "minus";
return "zero";
}
sign(5); // → "plus"
sign(0); // → "zero"function deliveryPrice(total) {
if (total >= 100) return 0;
if (total >= 30) return 5;
return 9;
}
deliveryPrice(150); // → 0
deliveryPrice(50); // → 5
deliveryPrice(10); // → 9elsefunction grade(score) {
if (score >= 90) return "excellent";
else if (score >= 60) return "good";
else return "try again";
}
grade(95); // → "excellent"
grade(70); // → "good"else if chain is checked top to bottomconst age = 20;
const label = age >= 18 ? "adult" : "teen";
label; // → "adult"? : is a short if...else that produces a valueResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
if (condition) evaluates the condition and turns it into true or false. If it's true, the block after if runs; otherwise the block after else (if there is one). Only one branch runs.
An else if chain checks conditions top to bottom and stops at the first true one — so order matters: narrower conditions go higher.
Any value can be a condition, not just a comparison. false, 0, "", null, undefined and NaN count as "falsy"; every other value is "truthy" (even "0" and an empty array []).
If a branch has a single statement you can drop the braces, but braces are safer: it's easy to add a second line later without breaking the logic.
Traps
How it differs from…
- Comparison:
===,!==,<,> The condition inside an
ifis usually built from comparisons: ===,<,>=.
When to pick something else
When there are many options and each just picks a value (country code → name), a long else if chain is worse than a lookup object: names[code]. And for choosing between two values, the ternary operator ? : is handier.