Skip to content

Type Casting, Converting & Coercion

JavaScript converts values from one type to another in two ways. Explicit conversion, often called casting, is when your code asks for it, as in Number('42'). Implicit conversion, or coercion, is when an operator needs a particular type and converts its operands without being asked, as in '6' * 2. Both follow the same rules, so knowing the rules explains most of JavaScript’s surprising results.

The functions String(), Number() and Boolean(), called without new, convert any value to that type. The unary + and !! are shorthands for Number() and Boolean(), as Unary & Double Bang Casting explains.

This example converts a range of values and prints each result as [string, number, boolean]:

const values = ['', '3.5', 'abc', 0, 1, true, false, null, undefined, NaN, [], [7], [1, 2], {}];
for (const v of values) {
console.log([String(v), Number(v), Boolean(v)]);
}

This prints:

[ '', 0, false ]
[ '3.5', 3.5, true ]
[ 'abc', NaN, true ]
[ '0', 0, false ]
[ '1', 1, true ]
[ 'true', 1, true ]
[ 'false', 0, false ]
[ 'null', 0, false ]
[ 'undefined', NaN, false ]
[ 'NaN', NaN, false ]
[ '', 0, true ]
[ '7', 7, true ]
[ '1,2', NaN, true ]
[ '[object Object]', NaN, true ]

A few results are worth remembering:

  • Strings to numbers: an empty string becomes 0, and text that is not wholly a number becomes NaN. parseInt and parseFloat are more forgiving, because they read digits from the left and stop at the first character that does not fit. See parseInt & parseFloat.
  • null and undefined: null becomes 0, while undefined becomes NaN.
  • Arrays: an array converts to a number by way of its string form, so [] becomes '' and then 0, [7] becomes '7' and then 7, and any longer array gives NaN.
  • Booleans: every object and array is truthy, even an empty one. The falsy values are false, 0, -0, 0n, '', null, undefined and NaN.

String(value) and value.toString() usually agree, but String() also works on null and undefined, where calling a method would throw a TypeError.

+ both adds numbers and joins strings. If either operand is a string after objects have been converted to primitives, it joins them as strings; otherwise it converts both to numbers and adds them. The other arithmetic operators, -, *, / and %, only do arithmetic, so they always convert to numbers.

const price = 4;
const label = 'Total: ';
console.log(label + price);
console.log(price + true);
console.log('6' - 2, '6' * '2', '6' / 'x');
console.log(1 + 2 + '3', '1' + 2 + 3);

This prints:

Total: 4
5
4 12 NaN
33 123

The last line shows that + works left to right. 1 + 2 is added first, and the result is then joined to '3', while in '1' + 2 + 3 the string comes first, so both numbers are joined to it. A template literal avoids the question, because it always produces a string. String Concatenation has more on joining strings.

The relational operators <, >, <= and >= compare two strings character by character, but convert to numbers when either side is not a string. Loose equality == also converts, by a separate set of rules that are hard to predict.

console.log('10' > 9);
console.log('10' > '9');
console.log(0 == '', 0 == '0', '' == '0');
console.log(null >= 0, null == 0);

This prints:

true
false
true true false
true false

'10' > '9' is false because '1' sorts before '9'. The third line shows that == is not transitive, and the last line shows that null >= 0 and null == 0 disagree, because >= converts null to a number but == does not. Use ===, which never converts, and convert values yourself before comparing them. See Double vs Triple Equals.

When an operator needs a primitive from an object, JavaScript calls the object’s valueOf or toString method. For arithmetic and comparisons, it tries valueOf first, and for a template literal or String(), it tries toString first. Defining these methods controls how your own objects convert.

const temperature = {
celsius: 21,
valueOf() {
return this.celsius;
},
toString() {
return `${this.celsius}°C`;
},
};
console.log(temperature + 1);
console.log(`${temperature}`);
console.log(String(temperature));
console.log(temperature > 20);

This prints:

22
21°C
21°C
true

A method named with the well-known symbol Symbol.toPrimitive takes priority over both, and receives a hint saying which type is wanted.

Calling Boolean, Number or String with new creates a wrapper object rather than a primitive. An object is always truthy, so a Boolean wrapper holding false still passes an if test.

const flag = new Boolean(false);
console.log(typeof flag);
console.log(Boolean(flag));
console.log(flag ? 'truthy' : 'falsy');
console.log('hello'.toUpperCase());

This prints:

object
true
truthy
HELLO

There is no reason to create wrappers yourself. JavaScript creates one briefly behind the scenes whenever a method is called on a primitive, which is why 'hello'.toUpperCase() works, and then discards it.

Steve Griffith covers this topic in his video JS Type Casting, Converting, and Coercion.