Skip to content
  • Type Coercion & == vs === · JavaScript

Type Coercion & == vs ===

LearnViaNotes @learnvianotes· 3 min read

JavaScript silently converts values when an operator expects another type. Learn the three conversions (to string, number, boolean) and == stops being magic.

Explicit conversion

JavaScript
console.log(String(123), String(null), String([1, 2]), String({}));
console.log(Number("42"), Number(""), Number("  7  "), Number("4px"));
console.log(Number(true), Number(null), Number(undefined), Number([]), Number([5]));
console.log(parseInt("4px"), parseFloat("3.5em"), parseInt("0x1F"), parseInt("101", 2));
console.log(Boolean(""), Boolean("0"), Boolean([]), Boolean(0));
Output
123 null 1,2 [object Object]
42 0 7 NaN
1 0 NaN 0 5
4 3.5 31 5
false true true false
ValueNumber(v)String(v)Boolean(v)
undefinedNaN"undefined"false
null0"null"false
true / false1 / 0"true" / "false"same
""0""false
"12abc"NaNsametrue
[]0""true
{}NaN"[object Object]"true

Implicit coercion by operators

  • + with any string operand → string concatenation. Otherwise numeric addition.

  • - * / % ** and unary + → always numeric.

  • if, !, &&, ||, ? : → boolean (truthiness).

  • Objects are first turned into primitives via Symbol.toPrimitive, then valueOf(), then toString().

JavaScript
console.log(1 + "2", "3" - 1, "3" * "4", +"5", +"");
console.log(true + 1, null + 1, undefined + 1);
console.log([] + [], [] + {}, [1, 2] + [3]);
console.log(1 + 2 + "3", "1" + 2 + 3);
Output
12 2 12 5 0
2 1 NaN
 [object Object] 1,23
33 123

== (loose) vs === (strict)

JavaScript
console.log(0 == "", 0 == "0", "" == "0");
console.log(false == "0", false == [], null == 0, null == undefined);
console.log([1] == 1, [1, 2] == "1,2", NaN == NaN);
console.log(0 === "", null === undefined, 1 === 1.0);
Output
true true false
true true false true
true true false
false false true

Object.is — SameValue

JavaScript
console.log(NaN === NaN, Object.is(NaN, NaN));
console.log(0 === -0, Object.is(0, -0));
console.log([NaN].includes(NaN), [NaN].indexOf(NaN));
Output
false true
true false
true -1
AlgorithmUsed byNaN vs NaN0 vs -0
Strict (===)===, indexOf, switchnot equalequal
SameValueZeroincludes, Map/Set keysequalequal
SameValueObject.isequalnot equal

Objects to primitives

JavaScript
const price = {
  valueOf() { return 42; },
  toString() { return "$42"; },
};
console.log(price + 1, `${price}`, price > 40);

const temp = {
  [Symbol.toPrimitive](hint) {
    return hint === "number" ? 21 : hint === "string" ? "21°C" : "default";
  },
};
console.log(+temp, `${temp}`, temp + "");
Output
43 $42 true
21 21°C default

What is the difference between == and ===?

What does [] + {} evaluate to?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report