Skip to content
jshacks.dev
Fundamentals

How Type Coercion Works in JavaScript With Every Rule

JavaScript coerces values by three rules: to string, to number and to boolean. See which operator picks which rule, with the result of each.

7 min read
Summarize in AI
Flat illustration of a form with one field rejected, with the JavaScript, Vite and TypeScript logos.

"JavaScript's type system is random" is the folk summary, and the evidence is a list of expressions like [] + {}. Every one of those results follows from three conversion rules and a short list of which operator uses which. Once you hold the rules, you can predict any of them, and more usefully, you can see which line in your own code relies on one by accident. This post sets out the rules and applies them to the operators you use daily, with output from Node.js 24. The related tables are in the truthy and falsy list and the post on loose equality, and everything sits within the guide to types and coercion.

The three targets

A coercion is a request to turn a value into a string, a number or a boolean. Each has a fixed rule per input type.

InputTo stringTo numberTo boolean
undefined"undefined"NaNfalse
null"null"0false
true / false"true" / "false"1 / 0itself
numberits decimal textitselffalse for 0, -0, NaN
stringitselfparsed, or NaNfalse for ""
symbolthrows for implicitthrowstrue
objectvia toString()via valueOf() firsttrue

The object row is the complicated one, because an object converts to a primitive first and then to the target. The post on converting objects to primitives covers it. For the rest, the table is complete. The symbol row throws on implicit conversion, which is one of the few places the language refuses to guess.

JavaScript
console.log(String(null), String(undefined), String(true));
console.log(Number(null), Number(undefined), Number(true));
console.log(Number(""), Number(" "), Number("12px"), Number("0x1f"));
console.log(Number("1e3"), Number("  42  "), Number("Infinity"));
console.log(Boolean(""), Boolean(" "), Boolean("0"));
Text
null undefined true
0 NaN 1
0 0 NaN 31
1000 42 Infinity
false true true

String to number conversion trims whitespace, accepts hex with 0x, accepts exponent notation, and rejects anything with trailing text. An empty or blank string becomes 0, which is the cause of the form bug where a blank field is counted as zero.

Which operator picks which target

The first group is the arithmetic operators other than +, which always convert to numbers.

JavaScript
console.log("5" - 3);
console.log("5" * "2");
console.log("10" / 4);
console.log("7" % 4);
console.log(true + 1);
console.log(null + 1);
console.log(undefined + 1);
console.log(+"42");
console.log(+"");
console.log(+[]);
Text
2
10
2.5
3
2
1
NaN
42
0
0

"5" - 3 is 2 because - can only subtract numbers. The unary plus is the shortest conversion to a number, and it works on anything: +"" is 0, +[] is 0 because an empty array converts to the empty string and then to zero. A string that is not numeric turns the whole result into NaN, a value covered in the post on NaN.

The + operator is different, because it serves two jobs. After converting both operands to primitives, if either is a string, it concatenates. Otherwise it adds numbers.

JavaScript
console.log("5" + 3);
console.log(5 + 3);
console.log(1 + 2 + "3");
console.log("1" + 2 + 3);
console.log([] + []);
console.log([1, 2] + [3]);
console.log({} + "");
console.log(null + "x");
Text
53
8
33
123

1,23
[object Object]
nullx

Evaluation goes left to right. 1 + 2 + "3" adds first, giving 3, then concatenates, giving "33". "1" + 2 + 3 concatenates immediately and stays a string. The array cases convert through toString(), which joins the items with commas, so [1, 2] + [3] is "1,2" + "3". The blank line in the output is the result of [] + [], an empty string.

Comparison operators

Relational operators convert to numbers unless both sides are strings, in which case they compare as strings, character by character.

JavaScript
console.log(3 > "12");
console.log("3" > "12");
console.log("a" < "b");
console.log("B" < "a");
console.log(null >= 0);
console.log(undefined >= 0);
Text
false
true
true
true
true
false

3 > "12" converts the string to 12 and compares numbers. "3" > "12" compares two strings, and "3" sorts after "1", so the result is true. Uppercase letters sort before lowercase because the comparison is by UTF-16 code unit. The last two lines show a quirk: null >= 0 is true because null converts to 0, but null == 0 is false because loose equality has its own rule for null. Sorting a list of numbers with the default sort() hits the string rule: it sorts [10, 9, 1] as strings, which gives [1, 10, 9]. Pass a numeric comparator.

Conditions and logical operators

if, while, ?: and ! convert to boolean. && and || convert their left operand to boolean to decide, and return the original operand.

JavaScript
console.log(!"");
console.log(!!"text");
console.log("" || "default");
console.log("a" && "b");
console.log(0 ?? "x");
Text
true
true
default
b
0

The double negation is the old way to write Boolean(value), and the function call is clearer. The distinction between || and ?? matters because || uses the boolean conversion and ?? tests for null and undefined, as covered in the post on nullish coalescing.

Template literals and symbols

Template literals convert every interpolation to a string, with the same rules as String() for primitives, and a symbol is the exception that throws.

JavaScript
const price = 9.5;
const tags = ["a", "b"];

console.log(`${price} ${tags} ${null} ${undefined}`);

try {
  console.log(`${Symbol("id")}`);
} catch (error) {
  console.log(error.message);
}

console.log(String(Symbol("id")));
Text
9.5 a,b null undefined
Cannot convert a Symbol value to a string
Symbol(id)

A template that interpolates an array prints its items joined by commas, and an object prints [object Object]. If the output is going to a user or a log, convert deliberately: JSON.stringify() for data, a formatter for numbers, join for lists. The explicit String(symbol) works because it is a conscious request.

Explicit conversion at the boundary

The rule we apply is to convert once, where data enters the program, and never rely on an operator to do it later.

JavaScript
function parseQuantity(text) {
  const trimmed = String(text).trim();
  const value = Number(trimmed);
  return trimmed !== "" && Number.isFinite(value) ? value : null;
}

console.log(parseQuantity("12"));
console.log(parseQuantity(""));
console.log(parseQuantity("12px"));
console.log(parseInt("12px", 10));
console.log(parseFloat("3.5kg"));
Text
12
null
null
12
3.5

Number() is strict, so it rejects trailing text. parseInt() and parseFloat() read a numeric prefix and ignore the rest, which is the right tool for a value like "3.5kg" and the wrong one for validation. Always pass the radix to parseInt(): parseInt("08", 10) is explicit and avoids the old octal confusion.

Reading a surprising result

When an expression gives an answer you did not expect, work through it in four questions. Which operator is it, since that fixes the target type? What type is each operand, because a primitive of the target type needs no conversion? Does an operand need converting, and by which row of the table? And did a conversion fail quietly, as with NaN or a blank string that became zero? Almost every puzzle in a list of "JavaScript wat" examples dissolves under these questions, which is a good way to turn trivia into skill.

Do the exercise on your own code. Pick a bug that came from a comparison or a sum, write the types on each side, and find the line where a string became a number or the reverse. The fix is nearly always an explicit conversion at the point the value entered.

Sorting is a coercion problem

The default sort() converts items to strings and compares them by code unit, so it has the same trap as the comparison operators and is the most common place the rule bites.

JavaScript
const scores = [10, 9, 100, 1];

console.log([...scores].sort());
console.log([...scores].sort((a, b) => a - b));
console.log(["b", "a", "B", "A"].sort());
Text
[ 1, 10, 100, 9 ]
[ 1, 9, 10, 100 ]
[ 'A', 'B', 'a', 'b' ]

The first sort puts 100 before 9, because "100" starts with "1". The comparator version converts to numbers through subtraction, and gives the right order. The string sort puts uppercase before lowercase for the same reason. For text that people read, use localeCompare() or Intl.Collator, which sort by language rules and not by code unit, and the comparator must return a number, so (a, b) => a > b is a bug that returns booleans and sorts unpredictably.

Whenever a result looks "almost sorted" or "almost right", ask which side converted to a string. The answer is usually in the first operator that touches the data.

Where coercion is fine

A few implicit conversions are idiomatic and safe. Template literals for building strings, if (items.length) for non-zero checks on a number and value == null for missing are all clear to any reader. The risk is where the reader cannot see the type: a function parameter that might be a string or a number, and an operator that reads differently depending on which arrives.

TypeScript removes most of the guessing, because the compiler tracks the types and rejects arithmetic on a string. It does not remove runtime coercion for data from outside the program, so the boundary conversion above still applies.

The conversions are defined in the specification under type conversion, and MDN's glossary entry for type coercion is a good short reference.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.