Types & Coercion

How JavaScript converts between types — ToPrimitive, ToNumber, ToString and ToBoolean, truthy and falsy values, == vs ===, the + operator, NaN, Object.is, and the infamous WAT examples explained.

Intermediate 3 min readLesson 2 of 12 Interview Q&A

JavaScript is dynamically and weakly typed: values have types, variables don't, and the language implicitly converts values when an operation expects a different type. This coercion follows precise rules from the spec. Learn the few rules and the "WAT" examples become predictable.

The abstract operations

OperationConverts toUsed by
ToBooleantrue/falseif, !, &&, ||, ?:
ToNumbernumber-, *, /, <, unary +, == with numbers
ToStringstringTemplate literals, + when one side is a string, property keys
ToPrimitivea primitiveAny of the above when given an object

ToBoolean: the falsy list

Exactly eight values are falsy; everything else is truthy:

JavaScript
false, 0, -0, 0n, "", null, undefined, NaN

Truthy surprises: "0", "false", " ", [], {}, function(){}, new Boolean(false).

JavaScript
if ([]) console.log("empty arrays are truthy");    // runs
if (arr.length) { ... }                             // the right way to check for elements

ToNumber

ValueNumber
undefinedNaN
null0
true / false1 / 0
"", " "0
"42", " 42 "42
"42px", "abc"NaN
"0x1F"31
[]0 (via "")
[5]5 (via "5")
[1, 2]NaN (via "1,2")
{}NaN (via "[object Object]")
JavaScript
Number("42px");      // NaN — strict
parseInt("42px");    // 42  — parses a leading number
parseInt("08");      // 8 (always pass the radix: parseInt(s, 10))
+"3" + +"4";         // 7

ToPrimitive (objects → primitives)

When an object meets an operator, JS calls obj[Symbol.toPrimitive](hint) if defined; otherwise it tries valueOf() then toString() (for the "number"/"default" hint) or toString() then valueOf() (for the "string" hint). Plain objects' valueOf returns the object itself, so toString() wins: "[object Object]". Arrays' toString joins elements with commas. Dates prefer strings.

JavaScript
const price = {
  amount: 42,
  [Symbol.toPrimitive](hint) { return hint === "string" ? `$${this.amount}` : this.amount; },
};
`${price}`;    // "$42"
price * 2;     // 84

The + operator

+ is both addition and concatenation. After ToPrimitive on both sides: if either side is a string, concatenate; otherwise convert both to numbers and add.

JavaScript
1 + 2          // 3
"1" + 2        // "12"
1 + 2 + "3"    // "33"   (left to right: 3 + "3")
"3" + 1 + 2    // "312"
[] + []        // ""     ("" + "")
[] + {}        // "[object Object]"
1 + null       // 1
1 + undefined  // NaN
true + true    // 2
"5" - 2        // 3      (- only means subtraction: ToNumber)
"5" * "2"      // 10

== vs ===

=== (strict equality): no conversion. Different types → false.

== (loose equality) converts according to an algorithm:

  1. Same type → compare like ===.
  2. null == undefined → true (and they equal nothing else).
  3. Number vs string → convert the string to a number.
  4. Boolean vs anything → convert the boolean to a number first.
  5. Object vs primitive → ToPrimitive the object, then compare again.
JavaScript
0 == ""             // true   ("" → 0)
0 == "0"            // true
"" == "0"           // false  (both strings: compared as strings)
false == "0"        // true   (false → 0, "0" → 0)
false == []         // true   (false → 0, [] → "" → 0)
[] == ![]           // true   (![] is false → 0; [] → "" → 0)
null == 0           // false  (null only equals undefined)
null >= 0           // true   (relational operators DO convert null to 0!)
NaN == NaN          // false
[1, 2] == "1,2"     // true

NaN and special numbers

NaN ("not a number") is a number that results from invalid math. It's the only value not equal to itself.

JavaScript
NaN === NaN              // false
Number.isNaN(NaN)        // true  — correct check
isNaN("abc")             // true  — global isNaN coerces first: avoid
Number.isNaN("abc")      // false
[NaN].includes(NaN)      // true  (includes uses SameValueZero)
[NaN].indexOf(NaN)       // -1    (indexOf uses ===)

Object.is(NaN, NaN)      // true
Object.is(0, -0)         // false (=== says true)
1 / 0                    // Infinity
-1 / 0                   // -Infinity
ComparisonNaN, NaN0, -0Used by
===falsetrueMost code
SameValueZerotruetrueincludes, Map/Set keys
Object.is (SameValue)truefalseReact state comparison

Explicit conversion (prefer this)

JavaScript
String(42)          // "42"         (also works for null/undefined, unlike .toString())
Number("42")        // 42
Boolean("x")        // true;  !!value is the common shorthand
parseFloat("3.5kg") // 3.5
BigInt("123")       // 123n
(1234.5).toFixed(1) // "1234.5"

Checking types

JavaScript
typeof x === "string"
Array.isArray(x)
x instanceof Date                    // checks the prototype chain (fails across iframes/realms)
x === null
Object.prototype.toString.call(x)   // "[object Date]", "[object RegExp]"… robust tag
Number.isInteger(x); Number.isFinite(x)

For real type safety, use TypeScript (TypeScript basics) and validate external data at runtime (zod, valibot).

Key takeaways
  • Eight falsy values; everything else (including [] and "0") is truthy.
    • concatenates if either side is a string; other arithmetic operators convert to numbers.
  • == runs a conversion algorithm; use === except for the x == null idiom.
  • NaN is never equal to itself; use Number.isNaN or Object.is.
  • Convert explicitly with String(), Number(), Boolean().
Interview questions
QWhy is [] == ![] true?medium

![] is evaluated first: [] is truthy, so ![] is false. Now [] == false: the boolean converts to the number 0. Then the object [] goes through ToPrimitive, becoming the empty string "", which converts to 0. 0 == 0 is true.

QWhat is the difference between null and undefined?easy

undefined means a value was never assigned: uninitialised variables, missing properties and parameters, functions without a return. null is an explicit "no value" assigned by the programmer. typeof undefined is "undefined" while typeof null is "object" (a historic bug). They're loosely equal to each other but not strictly equal.