Type Coercion & Equality: Interview Traps
JS جاوااسکریپت

Type Coercion & Equality: Interview Traps

== vs ===, truthy/falsy values, and the weird outputs that separate prepared candidates from everyone else.

BugCast Admin··۵ دقیقه مطالعه

JavaScript's type coercion causes infamous interview trick questions. Knowing the rules behind ==, ===, and abstract comparisons keeps you calm under pressure.

Common Interview Questions

Q: Explain == vs ===

Answer: === checks type and value with no coercion. == performs abstract equality: if types differ, JavaScript converts operands (often to numbers or strings) before comparing. Prefer === unless you have a deliberate coercion reason.

Q: Why is [] == ![] true?

Answer: ![] is false (object is truthy, negated). [] == false coerces: array becomes '', then '' == false becomes 0 == 0 which is true. This is why === is safer.

Q: List common falsy values

Answer: false, 0, -0, 0n, '', null, undefined, and NaN. Everything else is truthy, including [], {}, and '0'.

Q: What does Object.is add over ===?

Answer: Object.is treats NaN as equal to itself and distinguishes +0 from -0. === already handles NaN as unequal to itself in practice, but Object.is matches SameValue semantics used internally.


Object.is(NaN, NaN); // true
Object.is(+0, -0);       // false

Key Points for Interviews

  • Always default to === in application code

  • null == undefined is true; both only equal each other with ==

  • Truthy/falsy checks are not the same as boolean coercion in all contexts

  • Number('') is 0; Number(null) is 0; Number(undefined) is NaN

  • Interviewers want you to explain coercion steps, not memorize every edge case

#coercion#equality#interview

مطالب مرتبط