← All concepts
Fundamentals: Part 1

Data Types and Coercion

JavaScript has a small set of built-in types, and it converts between them automatically when an operator expects a different one.

Loading visual…

Definition

JavaScript has seven primitive types (string, number, boolean, null, undefined, symbol, bigint) plus object, and `typeof` tells you which one a value currently is. Primitives are compared and copied by value, while objects (including arrays and functions) are reference types. Type coercion is the automatic conversion the engine performs when an operator or context expects a different type than the one it got. The `+` operator prefers strings: if either operand is a string, the other is converted to a string and the two are concatenated. Every other arithmetic operator (`-`, `*`, `/`) prefers numbers, so it converts both operands to numbers first. This is why `"5" + 1` produces the string `"51"` but `"5" - 1` produces the number `4`: the same numeric-looking string takes two different paths depending on which operator is asking.

Examples

typeof "hi";    // "string"
typeof 42;      // "number"
typeof true;    // "boolean"
typeof undefined; // "undefined"
typeof null;    // "object" (a long-standing quirk)

typeof reports the current type of a value; null famously reports "object" due to a bug preserved for compatibility.

"5" + 1;  // "51" (+ prefers strings, so 1 becomes "1")
"5" - 1;  // 4    (- prefers numbers, so "5" becomes 5)
"5" * "2"; // 10   (both operands coerce to numbers)

The operator decides the coercion direction: + concatenates when a string is involved, while -, *, and / always coerce toward numbers.

Number("42");   // 42
String(42);      // "42"
Boolean("");     // false

Number(), String(), and Boolean() perform the same conversions explicitly, which is clearer and safer than relying on an operator to coerce implicitly.

Where you see this

Practice this

Further reading