今日已更新 281 条资讯 | 累计 29734 条内容
关于我们

JavaScript Type Coercion — Output-Based Questions ([] + [], NaN === NaN & Friends)

Amit Kumar 2026年07月26日 14:25 10 次阅读 来源:Dev.to

After hoisting, interviewers love dropping one-liners like: console . log ([] + []); console . log ([] + {}); console . log ({} + []); console . log ( NaN === NaN ); …and watching whether you guess, freeze, or calmly walk the coercion rules. This post is only output-based type coercion / equality questions. Try each snippet yourself first. Answers are hidden — click Show answer when you’re ready. TL;DR — what interviewers are testing Concept Trap + with objects/arrays Often becomes string concat , not math [] / {} stringification [] → "" , {} → "[object Object]" Bare {} + [] Parser may treat {} as a block , not an object NaN === NaN Always false — use Number.isNaN / Object.is == vs === == coerces; === does not Falsy vs “empty-looking” [] and {} are truthy typeof null Infamous "object" lie One-line mental model + asks both sides to become primitives. If either side is a string (after that), you get concatenation . Otherwise you get number math — and weird values become NaN . Warm-up: how + really decides When JS hits a + b , it roughly does: 1) Convert both sides to primitives (ToPrimitive) 2) If either result is a string → String(a) + String(b) // concat 3) Else → Number(a) + Number(b) // math For plain objects / arrays, ToPrimitive usually ends up calling .toString() : Value String(value) Number(value) [] "" 0 [1, 2] "1,2" NaN {} "[object Object]" NaN null "null" 0 undefined "undefined" NaN true "true" 1 false "false" 0 That’s enough to solve most [] + {} style questions. How to use this post Read the snippet Say the output out loud (or write it down) Only then open Show answer Read the step-by-step — don’t only memorize the final print Q1 — Classic [] + [] console . log ([] + []); Show answer Output "" (empty string — looks like a blank line) Step by step + wants primitives from both arrays. String([]) → "" (empty array joins to empty string). "" + "" → "" . Interview tip: People often say 0 or [] . Wrong. Empty array stringifies to "" , so you get string concat o

本文内容来源于互联网,版权归原作者所有
查看原文