Conditionals
if/else, the ternary operator, switch, and truthy/falsy values in decisions.
Programs need to make decisions: show a discount if the cart is big enough, greet by time of day, reject an invalid password. JavaScript gives you if/else, the ternary operator, switch, and logical operators for this.
if, else if, else#
JavaScript checks each condition from top to bottom and runs the first block whose condition is truthy. The else block runs if none match. Order matters: put the most specific conditions first.
Always use braces, even for one-line bodies. Braces prevent a classic bug where a second line looks like it's inside the if but isn't.
Conditions are truthy or falsy#
The condition doesn't have to be a boolean. Falsy values are false, 0, -0, 0n, "", null, undefined and NaN; everything else is truthy.
An empty array
[]and empty object{}are truthy. Checkarr.length === 0orObject.keys(obj).length === 0for emptiness.
Combining conditions#
When conditions get long, name them:
Guard clauses: return early#
Deeply nested ifs are hard to read. In functions, handle the special cases first and return:
The "happy path" stays at the bottom, un-indented.
The ternary operator#
condition ? valueIfTrue : valueIfFalse is an expression — it produces a value:
Use ternaries for simple two-way choices. Nesting them (a ? b : c ? d : e) quickly becomes unreadable — switch to if/else or a lookup object.
switch#
switch compares one value against many cases using strict equality (===):
Stacking case "Saturday": and case "Sunday": lets both share one block. Outside a function, end each case with break:
Lookup objects: an alternative to long switches#
When you're just mapping values to values, an object is shorter:
Logical operators as mini-conditionals#
You'll often see && and ?? used as short conditionals:
cond && doSomething() is common in React JSX. In regular code, a plain if is usually clearer.
Comparing with ===, not =#
Common mistakes#
- Using
=instead of===in a condition. - Forgetting
breakin aswitch(fall-through). - Assuming
[]or"0"is falsy — both are truthy. - Writing
if (x === 1 || 2)— that's always truthy because2is truthy. Writex === 1 || x === 2, or[1, 2].includes(x).
What's next#
Decisions let your code choose a path. Next, loops let it repeat work — over numbers, arrays and objects.
Check your understanding
Quick quiz
1.What does this log?
const x = 0; if (x) { console.log("yes"); } else { console.log("no"); }2.In a
switch, what happens if you forgetbreakat the end of a matchingcase?3.Which is the idiomatic way to choose between two values in an expression?
Finished reading?
Mark this lesson complete to track your progress.