Coercion and operators
JavaScript is a weakly, dynamically typed language: when an operation meets operands of different types, the engine silently converts one to the other rather than throwing. That is type coercion. It saves lines, but it is exactly where all the famous memes come from, like 1 + '2' === '12' and [] == ![].
Coercion does not work in a vacuum — it happens inside operators, and each has its own rule: + pulls toward strings, comparisons pull toward numbers, logical operators return an operand with no coercion at all. This topic covers both the coercion rules themselves and the operator families that apply them. The full map is in the layers below.
Topic map
- Operators overview — categories (arithmetic, comparison, logic, bitwise), arity, precedence and associativity, the ternary and comma.
- Type coercion — implicit coercion to string and to number,
ToPrimitive, and a walk-through of[] == ![]. - Loose versus strict equality —
==with coercion versus===without it,NaN, and+0/-0. - Boolean coercion — the eight falsy values, truthy, and what
!!xdoes. - Logical operators —
&&,||,??: short-circuiting and returning an operand. - Unary operators —
typeof,delete,void,!, unary+/-,++/--. - Bitwise operators —
&,|,^,~, shifts, 32-bit truncation, and the~~trick.
Common traps
| Mistake | Consequence | ||||
|---|---|---|---|---|---|
Comparing with == instead of === | Silent coercion — 0 == '', 1 == '1', null == undefined are all true | ||||
Thinking &&/` | ` return a boolean | They return one of the operands, not true/false | |||
| Confusing ` | and ??` for defaults | `0 | 5 is 5, but 0 ?? 5 is 0 — ?? reacts only to null/undefined` | ||
Forgetting [] and {} are truthy | An empty array is truthy, yet [] == false is true via coercion | ||||
Expecting ~~x to round | ~~ truncates toward zero (like Math.trunc), it does not round | ||||
Relying on NaN == NaN | NaN equals nothing, including itself; check with Number.isNaN |
Interview relevance
Coercion is the favourite way to test whether you separate "magic" from mechanics. A candidate who calmly walks [] == ![] through the ToPrimitive and ToNumber steps is valued above one who memorised the answer true but cannot explain why.
Typical checks:
- The difference between
==and===and why===is preferred. - What
&&,||,??return and how they short-circuit. - The full list of the eight falsy values.
- What unary
+,!,typeof,void,deletedo. - How bitwise operators coerce to a 32-bit integer.
Common wrong answer: "&& returns true or false." In fact logical operators return an operand: 'a' && 'b' is 'b', and 0 || 'x' is 'x'. You only get a boolean if the operands are already booleans.