Conditions
Making your code choose between different paths based on a test.
What is it?
Programs make decisions: "if the user is logged in, show their name; otherwise, show a login button." Conditions are how you write that in code.
The main tool is the if statement. It runs a block only when a test is true, and offers alternatives with else if and else.
Explain like I'm 10
It's like a fork in the road with a sign: 'If it's raining, take the covered path. Otherwise, take the shortcut.' Your code reads the sign and picks a path.
Examples
if / else if / else
const hour = 14;
if (hour < 12) {
console.log("Good morning");
} else if (hour < 18) {
console.log("Good afternoon");
} else {
console.log("Good evening");
}
// logs: "Good afternoon"A ternary expression for a simple either/or
const age = 20;
const message = age >= 18 ? "You can vote" : "You can't vote yet";
console.log(message); // "You can vote"For a simple choice between two values, a ternary (condition ? ifTrue : ifFalse) is a one-line alternative to if/else.
How it works
JavaScript checks the condition in the parentheses. If it's truthy (anything except the "falsy" values false, 0, "", null, undefined and NaN), it runs that block and skips the rest.
Otherwise it moves to the next else if and checks again, finally falling into else if nothing matched.
Check condition
↓
true? ──yes──▶ run this block ──▶ done
│
no
↓
check next condition (repeat)Why does it exist?
A program that always does the same thing, whatever the input, isn't very useful. Conditions let code adapt to the current data or situation.
When to use it
Use conditions when the next step depends on data you don't know in advance: user input, an API value, the current time. If you can describe your logic with "if," it's a condition.
When not to use it
If every branch does almost the same thing, a simpler solution like a lookup object or a default value may avoid the repetition. A switch (or a lookup) also reads better than five or more else if blocks checking the same variable.
Common mistakes
Forgetting the
elseand assuming a variable is always set inside theifblock.Using
=instead of===inside a condition by accident.Writing deeply nested if/else chains instead of simplifying the logic.
Practice exercises
- Easy:
Write an
if/elsethat logs "even" or "odd" for a given number. - Medium:
Write a grading function that returns a letter grade (A/B/C/D/F) from a numeric score using
if/else if. - Hard:
Rewrite a chain of 4
else ifchecks using aswitchstatement instead.
Interview questions
What counts as a 'falsy' value in JavaScript, and how does that affect an `if` condition?
false, 0, -0, 0n, "" (empty string), null, undefined and NaN are the only falsy values. Everything else, including "0", [] and {}, is truthy. An if doesn't need a real boolean; it converts its condition to true/false with these rules.
What is a ternary operator?
A one-expression conditional: condition ? valueIfTrue : valueIfFalse. Unlike if/else, it produces a value, so you can use it directly in an assignment, a function argument or a template string.
When would you reach for `switch` instead of `if/else`?
When you compare one value against several known possibilities: a status code, a day of the week, a menu option. It often reads better than a long else if chain repeating the same variable. For a few branches, either is fine.
What's the difference between chaining `else if` and writing separate standalone `if` statements?
In an else if chain, only one branch runs; once a condition matches, the rest are skipped. Separate ifs are each checked and can all run, even if an earlier one matched, which is usually not what you want when conditions overlap.
What happens if an `if` condition isn't a literal `true` or `false`, like `if (user)`?
JavaScript converts the value to a boolean using the truthy/falsy rules. if (user) runs when user is truthy (an object, a non-empty string, a non-zero number) and skips for any falsy value. No === true needed.
Does `switch` compare its cases with `==` or `===`?
Strict equality (===). switch never converts types, so switch (1) { case "1": ... } won't match, even though 1 == "1" is true.
What is 'fallthrough' in a `switch` statement, and why does `break` matter?
Without a break, execution doesn't stop after a matching case: it falls into the next case's code and runs it too, until a break or the end of the switch. break makes each case an isolated branch.
Can you chain multiple `else if` blocks indefinitely? What decides which one actually runs?
Yes, there's no limit. JavaScript checks conditions top to bottom, runs the first truthy one and skips the rest of the chain, even if a later condition would also match.
What's the practical difference between nesting `if` statements and chaining them with `else if`?
Nested ifs check conditions that depend on each other (the inner check only matters once the outer one passed). An else if chain checks mutually exclusive alternatives for one decision. Deep nesting for what are really alternatives is harder to read than a flat chain.
Why might a lookup object be a better choice than a long `else if` chain?
When each branch just maps one input to one output (e.g. a status code to a message), a lookup object (messages[code]) replaces the chain with one property access. It's shorter, doesn't repeat the variable, and you extend it by adding a key.
Why does `if (0)` skip its block, but `if ("0")` run it?
The number 0 is falsy. The string "0" is non-empty, and every non-empty string is truthy, whatever its characters. String truthiness depends only on length.
Can a `switch` statement handle range checks or complex boolean conditions directly, like `age > 18`?
Not directly; switch matches fixed values with strict equality. A workaround is switch (true) { case age > 18: ... }, which compares each case expression with true. But an if/else if chain is usually clearer.
Beyond syntax, what's a real difference between a ternary and an `if/else` statement?
A ternary is an expression: it produces a value you can assign, pass as an argument or put in a string. An if/else is a statement that produces no value, so choosing a value with it means declaring a variable and assigning it in each branch.
Output-prediction: does `if ([]) console.log("truthy"); else console.log("falsy");` log "truthy" or "falsy", and why does that surprise people?
It logs "truthy". An empty array is an object, and every object (including [] and {}) is truthy, even when empty. Only the fixed falsy values (false, 0, "", null, undefined, NaN) are falsy.
Output-prediction: what does `switch (1) { case "1": console.log("string one"); break; case 1: console.log("number one"); break; default: console.log("none"); }` log?
It logs "number one". switch uses strict equality, so 1 doesn't match "1" (different types) but does match case 1.
Output-prediction: what does `let result; if (false) { result = "a"; } console.log(result);` log?
It logs undefined. The if body never runs and there's no else, so result is never assigned and stays undefined.
Trap: what's the bug in `switch (color) { case "red": console.log("stop"); case "green": console.log("go"); break; }`, and what does it print for `color = "red"`?
It prints "stop" and "go". The "red" case has no break, so execution falls through into the "green" code, even though color isn't "green".
Output-prediction: what does `age >= 18 ? "adult" : age >= 13 ? "teen" : "child"` evaluate to when `age` is `15`?
"teen". Nested ternaries work like chained else ifs: age >= 18 is false, so it moves to the second ternary, where age >= 13 is true, giving "teen".