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.
Explicit conversion
Section titled “Explicit conversion”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 becomesNaN.parseIntandparseFloatare more forgiving, because they read digits from the left and stop at the first character that does not fit. See parseInt & parseFloat. nullandundefined:nullbecomes0, whileundefinedbecomesNaN.- Arrays: an array converts to a number by way of its string form, so
[]becomes''and then0,[7]becomes'7'and then7, and any longer array givesNaN. - Booleans: every object and array is truthy, even an empty one. The falsy values are
false,0,-0,0n,'',null,undefinedandNaN.
String(value) and value.toString() usually agree, but String() also works on null and undefined, where calling a method would throw a TypeError.
The + operator
Section titled “The + operator”+ 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: 454 12 NaN33 123The 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.
Comparisons
Section titled “Comparisons”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:
truefalsetrue true falsetrue 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.
Objects and valueOf
Section titled “Objects and valueOf”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:
2221°C21°CtrueA method named with the well-known symbol Symbol.toPrimitive takes priority over both, and receives a hint saying which type is wanted.
Wrapper objects
Section titled “Wrapper objects”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:
objecttruetruthyHELLOThere 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.