Conditionals
If / Else — The Decision Maker
Imagine you're at a fork in the road. If it's raining, you grab an umbrella. Otherwise, you wear sunglasses. That's exactly what if / else does — it lets your code choose a path based on whether a condition is true or false.
You can chain multiple conditions with else if to handle more than two possibilities. JavaScript checks them top to bottom and runs the first block that matches.
If / Else If / Else
Truthy & Falsy — JavaScript's Weird Truth System
In JavaScript, if doesn't just work with true and false. It works with any value. JavaScript decides whether a value is "truthy" (treated as true) or "falsy" (treated as false).
There are exactly 7 falsy values. Everything else is truthy:
false— obviously0— zero is falsy-0— negative zero (yes, it exists)0n— BigInt zero""— empty stringnullundefinedNaN
Everything else — including "0" (string zero), [] (empty array), and {} (empty object) — is truthy. This trips up a lot of people!
Truthy/Falsy Surprises
Switch, Ternary & Nullish Coalescing
Switch is great when you're comparing one value against many possible matches — like a vending machine matching a button press to a drink.
The ternary operator (condition ? valueIfTrue : valueIfFalse) is a compact if/else that fits in a single expression. Perfect for assigning values based on a condition.
The nullish coalescing operator (??) provides a default value when something is null or undefined. It's more precise than || because it doesn't treat 0 or "" as "empty."