Question presented to candidate: "What's the difference between == and === in JavaScript, and why do most style guides tell you to always use ===?"
What a strong answer should cover:
- 📌 Interview term: loose equality (
==) — compares two values after converting them to a common type when their types differ. Verified directly:1 == "1"istruebecause the string is coerced to a number first. - 📌 Interview term: strict equality (
===) — compares both type and value, with no coercion at all. Verified:1 === "1"isfalsebecause a number and a string are never equal under===, regardless of their values. - A precise answer names the coercion rules that make
==unpredictable:null == undefinedistrue(a special-cased pair — they equal each other and nothing else under==),0 == falseistrue, and"" == falseistrue— verified directly. - 📌 Interview term: the classic gotcha —
[] == ![]evaluates totrue. Verified by tracing it step by step:![]evaluates first (an empty array is truthy, so!of it isfalse), leaving[] == false, which coerces the array to a primitive ("") and then to a number (0), matchingfalse's own0. NaN == NaNisfalseunder both operators — coercion never makesNaNequal to anything, including itself — verified directly.
Clarifying questions expected:
- None — this is a definitional/comparison question; the strong move is naming the coercion mechanism precisely rather than just "== is looser."
Code / implementation expected: Optional — walking through 2-3 concrete coercion examples (including the null == undefined special case) demonstrates real understanding better than reciting the rule from memory.