Search lands in PR-5.1 (Pagefind).

Reference Intermediate

Chapter 11 Updated

Tricky JS Interview Questions: Data Types, Type Coercion, Equality & Gotchas

Data types, type coercion, == vs ===, NaN, truthy/falsy — the JS gotchas.

  • Full 14m
  • Revision 3m
  • Flow 2m

8 data types

7 primitives + 1 reference.

  • Primitives (by value): number, string, boolean, undefined, null, symbol, bigint.
  • Reference: object — includes arrays, functions, dates, regex, Map, Set.
  • Primitives are immutable and compared by value; objects are mutable and compared by reference.
  • typeof null === "object" (historical bug); typeof [] is also "object" — use Array.isArray().

Type coercion rules

Implicit conversion when operators disagree.

  • + with any string → string concatenation wins. "5" + 3 + 2 === "532".
  • -, *, /, %, ** coerce to number. "5" - 3 === 2.
  • Numeric conversions to remember: true → 1, false → 0, null → 0, undefined → NaN, "" → 0.
  • Unary + is the short form of Number(): +"5" === 5, +"abc" === NaN.

== vs === (and ??)

Always use strict.

  • == coerces types before comparing; === requires type + value match.
  • null == undefined is true, but neither equals anything else with ==.
  • NaN is the only value not equal to itself — use Number.isNaN() or Object.is().
  • ?? returns the right side only for null/undefined; || triggers on any falsy value.

8 falsy values (memorize!)

Everything else is truthy.

  • false, 0, -0, 0n, "", null, undefined, NaN — that’s the whole list.
  • Common truthy traps: "0", "false", [], {}, " " (space), -1, Infinity.
  • new Boolean(false) is truthy because it’s an object — never use new Boolean/String/Number.
  • !!value is the idiomatic way to coerce to a real boolean.

The famous quirks

What interviewers love to ask.

  • [] == ![]true. ![] is false, then []""0, false0, 0 == 0.
  • null >= 0 is true but null == 0 is false (different comparison algorithms).
  • "2" > "12" is true (string lexicographic), but "2" > 12 is false (numeric).
  • 0.1 + 0.2 !== 0.3 — IEEE 754 floating-point precision.

Logical operators return operands

Not booleans.

  • || returns the first truthy value (or the last value if all are falsy).
  • && returns the first falsy value (or the last value if all are truthy).
  • 0 || 42 === 42; "hello" && "world" === "world".
  • Objects used as keys become the string "[object Object]" — all object keys collide!

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.