Type Conversion and Coercion
Type conversion is changing a value from one type to another. When you do it on purpose, with Number("45") or String(120), it is explicit conversion. When JavaScript does it automatically because an operator needs a different type, as in "5" * 2, it is implicit conversion, usually called coercion. Coercion follows fixed rules, and once you know the three target types (string, number, boolean) and how objects become primitives, every famous puzzle like [] + {} becomes predictable. The practical lesson is the opposite: convert explicitly so you never depend on these rules.
In One Minute
- Convert explicitly with
String(x),Number(x)andBoolean(x)(or!!x). +with any string operand joins strings;-,*,/,%and**convert to numbers.- Conditions (
if,&&,||,!) convert to booleans using truthy and falsy rules. ==converts both sides by a long set of rules;===never converts.- Objects become primitives through ToPrimitive:
Symbol.toPrimitive, thenvalueOf, thentoString.
Explicit Conversion
To String
console.log(String(120), String(true), String(null), String(undefined));
console.log(String([1, 2, 3]), String({}), String([]));
console.log((120).toString(), `${45.5}`);120 true null undefined
1,2,3 [object Object]
120 45.5String([]) is the empty string (printed as nothing at the end of the second line). Arrays join their items with commas; plain objects become "[object Object]". String(x) works for every value, including null and undefined, while x.toString() throws on those two.
To Number
| Value | Number(value) |
|---|---|
"120", " 120 " | 120 |
"", " " | 0 |
"12px", "abc" | NaN |
true / false | 1 / 0 |
null | 0 |
undefined | NaN |
[] | 0 |
[7] | 7 |
[1, 2], {} | NaN |
console.log(Number("120"), Number(""), Number("12px"));
console.log(Number(true), Number(null), Number(undefined));
console.log(Number([]), Number([7]), Number([1, 2]), Number({}));
console.log(+"45", +true, +"");120 0 NaN
1 0 NaN
0 7 NaN NaN
45 1 0The unary plus +x does the same as Number(x), and you will see it in compact code. Note the traps: "" and null become 0, not NaN.
To Boolean
Boolean(x) follows the truthy and falsy rules: the eight falsy values (false, 0, -0, 0n, "", null, undefined, NaN) become false; everything else, including "0", "false", [] and {}, becomes true.
Implicit Coercion
The + Operator
+ is the trickiest operator because it does two jobs. After converting both operands to primitives, if either one is a string, it joins them as strings; otherwise it adds them as numbers:
console.log(1 + "2");
console.log("3" + 4 + 5);
console.log(3 + 4 + "5");
console.log(true + 1);
console.log(null + 1);
console.log(undefined + 1);
console.log([1, 2] + [3]);12
345
75
2
1
NaN
1,23Explanation: evaluation goes left to right. In 3 + 4 + "5", 3 + 4 is 7 first, then 7 + "5" is "75". true becomes 1 and null becomes 0 when no string is involved. Arrays become strings ("1,2" and "3"), so they join.
Other Arithmetic Operators
-, *, /, % and ** only do math, so they always convert to numbers:
console.log("10" - 4);
console.log("6" * "7");
console.log("10" / "4");
console.log("abc" - 1);
console.log([] - 1, [5] * 2);6
42
2.5
NaN
-1 10Comparisons
Relational operators (<, >, <=, >=) compare two strings as strings, and anything else as numbers. Loose equality == has its own rules: null and undefined equal only each other; booleans convert to numbers; a string compared with a number converts to a number; an object compared with a primitive converts to a primitive.
console.log("10" < "9", "10" < 9);
console.log(null == 0, null >= 0, undefined == null);
console.log("1" == 1, true == 1, "true" == true);
console.log([] == 0, [] == "", [0] == false);true false
false true true
true true false
true true true"true" == true is false because true becomes 1, then "true" becomes NaN. Every line here is a reason to use ===.
How Objects Become Primitives
When an object meets an operator that needs a primitive, JavaScript runs the ToPrimitive operation with a hint: "number" (for math and comparisons), "string" (for template literals and String()), or "default" (for + and ==). It then tries, in order:
- The object's
[Symbol.toPrimitive](hint)method, if it has one. - For the
"string"hint:toString(), thenvalueOf(). For the others:valueOf(), thentoString(). - The first one that returns a primitive wins. If neither does, a
TypeErroris thrown.
Plain objects and arrays have a valueOf that returns the object itself (not a primitive), so in practice their toString is used: "[object Object]" and the comma-joined items.
const fee = {
amount: 120,
valueOf() { return this.amount; },
toString() { return `$${this.amount}`; },
};
console.log(fee + 5);
console.log(fee * 2);
console.log(`${fee}`);
console.log(String(fee));
const money = {
[Symbol.toPrimitive](hint) {
return hint === "number" ? 45 : hint === "string" ? "forty-five dollars" : "default";
},
};
console.log(+money, `${money}`, money + "");125
240
$120
$120
45 forty-five dollars defaultExplanation: + and * use the "default" and "number" hints, which try valueOf first, so fee acts as 120. Template literals and String() use the "string" hint, which tries toString first. Symbol.toPrimitive overrides both and receives the hint directly. Date objects use the "string" order even for +, which is why date + 1 joins text instead of adding a millisecond.
The Classic Puzzles
console.log([] + []);
console.log([] + {});
console.log({} + []);
console.log([] == ![]);
console.log("b" + "a" + +"a" + "a");
[object Object]
[object Object]
true
baNaNaExplanation, line by line:
[] + []: both arrays become"", and"" + ""is the empty string (the blank first line).[] + {}:""+"[object Object]".{} + []: inside an expression like aconsole.logargument,{}is an object, so the result is the same as line 2. (Typed alone at the start of a console line,{}is read as an empty block, and the line becomes+[], which is0. Same characters, different meaning.)[] == ![]:![]isfalse(arrays are truthy). Then[] == falseconverts both to numbers:0 == 0, which istrue.+"a"isNaN, so the string becomes"ba" + "NaN" + "a".
In Practice
The Fee Tracker reads query parameters such as ?grade=9&show=1&limit=, which are always strings. It converts each one explicitly with a clear rule, instead of letting coercion guess:
const params = new URLSearchParams("grade=9&show=1&limit=&min=abc");
function intParam(name, fallback) {
const raw = params.get(name);
if (raw === null || raw.trim() === "") return fallback;
const n = Number(raw);
return Number.isInteger(n) ? n : fallback;
}
const boolParam = (name) => ["1", "true", "yes"].includes(params.get(name) ?? "");
console.log(intParam("grade", null), intParam("limit", 25), intParam("min", 0));
console.log(boolParam("show"), boolParam("hidden"));9 25 0
true falseWithout the explicit checks, Number("") would turn the empty limit into 0 instead of the default, and Boolean("0") would turn show=0 into true.
Common Mistakes
Adding form values with +. They join as strings. Convert with Number first.
Relying on ==. Its rules are inconsistent. Use === after converting.
Treating Number("") and Number(null) as invalid. Both are 0. Check for empty input separately.
Using x.toString() on values that may be null or undefined. It throws. Use String(x).
Under the Hood
The specification defines a small set of abstract operations that all coercion goes through: ToPrimitive, ToString, ToNumber, ToNumeric (number or BigInt), ToBoolean, ToPropertyKey and ToObject. Every operator is defined in terms of them. For example, the + operator calls ToPrimitive on both operands with no hint, checks whether either result is a string, and then calls either ToString on both or ToNumeric on both. The == operator is the IsLooselyEqual algorithm, about a dozen steps of type-dependent conversions. === is IsStrictlyEqual, which returns false immediately when the types differ.
Knowing that these few operations exist is enough to reason about any expression: identify which operation each operator calls, apply it, and continue. It is also why engines can optimize coercion-free code better: when an operator always sees two numbers, V8 can skip all of these steps and emit a single machine instruction.
Interview Corner
What is the difference between type conversion and type coercion?
Conversion usually means explicit conversion (Number(x), String(x)). Coercion is implicit conversion performed by operators: + coerces to string if either primitive operand is a string, other arithmetic operators coerce to number, conditions coerce to boolean, and == follows the IsLooselyEqual algorithm.
Why is [] + {} equal to "[object Object]"?
Both operands go through ToPrimitive with the default hint. Arrays and plain objects have valueOf returning themselves, so toString is used: [] becomes "" and {} becomes "[object Object]". Since a string is involved, + concatenates.
Why is [] == ![] true?
![] is false because objects are truthy. Then [] == false: the boolean becomes 0, the array goes through ToPrimitive to "", which becomes 0. 0 == 0 is true.
Practice
Challenge: Predict each result before running: "5" + 3, "5" - 3, "5" * "2", true + true, [] + 1, [2] * [3]. Then write the explicit-conversion version of "5" + 3 that gives 8.
Show solution
console.log("5" + 3, "5" - 3, "5" * "2", true + true, [] + 1, [2] * [3]);
console.log(Number("5") + 3);53 2 10 2 1 6
8Key Takeaways
| Expression | Result | Why |
|---|---|---|
"1" + 2 | "12" | + joins with a string |
"6" - 2 | 4 | - converts to numbers |
[] + {} | "[object Object]" | Both become strings |
null + 1 | 1 | null becomes 0 |
undefined + 1 | NaN | undefined becomes NaN |
Was this tutorial helpful?