JavaScript Type Coercion: Key Rules Behind Tricky Interview Output Questions
JavaScript type coercion frequently trips up developers in technical interviews, particularly with expressions involving arrays, objects, and special values like NaN. When the + operator is used with arrays or objects, JavaScript converts both sides to primitives via ToPrimitive, defaulting to string concatenation if either result is a string. For example, [] + [] produces an empty string, while [] + {} yields "[object Object]" because arrays stringify to "" and plain objects to "[object Object]". A bare {} + [] at statement level can be parsed as an empty block followed by unary +[], evaluating to 0, whereas wrapping it in parentheses forces object interpretation and returns "[object Object]". NaN is never equal to itself under IEEE-754, making both NaN === NaN and NaN == NaN return false, so developers should use Number.isNaN() or Object.is() for reliable NaN checks.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in