Types, Coercion and Equality

Understand how JavaScript converts values behind your back, what truthy and falsy mean, and how references differ from values.

Beginner · about 4 hours · difficulty 2/5

Learn first: JavaScript Syntax and Fundamentals

JavaScript is dynamically typed and very willing to convert values for you. That flexibility causes a whole genre of bugs, and interviewers love it.

Implicit coercion

  • "5" + 1 is "51" (string concatenation wins), but "5" - 1 is 4 (numeric).
  • == coerces before comparing: 0 == "" and null == undefined are true. === never coerces, so use it by default.
  • NaN is not equal to itself; check with Number.isNaN().
  • Floating point: 0.1 + 0.2 !== 0.3. For money, work in integer cents.

Truthy and falsy

The falsy values are false, 0, -0, 0n, "", null, undefined and NaN. Everything else, including [], {} and "0", is truthy. This is why count || 10 breaks when count is 0, and why ?? exists: it only falls back on null or undefined.

Values vs references

Primitives are copied by value. Objects and arrays are held by reference: assigning or passing them shares the same underlying object, so mutating one "copy" mutates both. Spread ({...obj}) makes a shallow copy; structuredClone() makes a deep one. This distinction is exactly why React insists you never mutate state.

Checking types

typeof works for primitives (but typeof null is "object", a historic bug); use Array.isArray() for arrays and instanceof for class instances.

Move on when you can predict the output of ten tricky coercion snippets and explain why mutating an object passed into a function affects the caller.

Key concepts

  • typeof and type checks
  • Implicit vs explicit conversion
  • == vs ===
  • Truthy and falsy values
  • ?? vs ||
  • Value vs reference
  • Shallow vs deep copies: spread vs structuredClone
  • Floating point and NaN

Mini project

Write a set of 15 console assertions covering coercion, equality and copying edge cases, each with a comment explaining the result; then fix a buggy function that mutates its input.

Check yourself

Why does quantity || 1 misbehave when quantity is 0, and what should you write instead?

Free resources