Skip to content
Conditionals: if, else if, else
step 1/6

Reading — step 1 of 6

Learn

~3 min readControl Flow

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

js

The first matching branch runs; the rest are skipped. Order matters — check the most specific or strictest condition FIRST.

Comparison operators

js

⚠️ Always use === and !==

Never use == or !=. They do silent type coercion that causes real bugs:

js

=== checks both type AND value. ESLint warns on == for a reason — make it a habit.

Logical operators

js

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.

js

The ternary

For short decisions:

js

Reads as: "score >= 60 ? then 'pass' : else 'fail'." Avoid nesting — chained ternaries get ugly fast.

Nullish coalescing — ?? vs ||

js

?? 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

js

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 break in switch — 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…