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.