Reading — step 1 of 6
Learn
Real programs make decisions. JavaScript's if runs a block when a condition is truthy, skips it otherwise. Chain with else if; finish with else for the fallback.
Basic shape
The first matching branch runs; the rest are skipped. Order matters — check the most specific or strictest condition FIRST.
Comparison operators
⚠️ Always use === and !==
Never use == or !=. They do silent type coercion that causes real bugs:
=== checks both type AND value. ESLint warns on == for a reason — make it a habit.
Logical operators
Note && and || return values, not booleans! "hello" || "world" is "hello", not true.
Truthy and falsy
In a boolean context (like if), JavaScript checks if a value is truthy or falsy:
Falsy (just these 7): false, 0, -0, "", null, undefined, NaN.
Truthy: everything else, including "0", "false", [], {}. Yes, even empty arrays and objects are TRUTHY.
The ternary
For short decisions:
Reads as: "score >= 60 ? then 'pass' : else 'fail'." Avoid nesting — chained ternaries get ugly fast.
Nullish coalescing — ?? vs ||
?? only treats null and undefined as missing. || treats 0 and "" as missing too. Use ?? when 0 or "" are valid values.
Switch — for many discrete cases
Don't forget break — without it, execution "falls through" to the next case. (Sometimes this is intentional, as in the example.)
Common mistakes
- Using
==instead of===— type coercion bites. - Forgetting
breakinswitch— silent fall-through bugs. - Treating
[]and{}as falsy — they're truthy. if (a = b)— a single=is assignment! Always returns the assigned value.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…