Automatic Type Conversions
suggest changeBeware that numbers can accidentally be converted to strings or NaN (Not a Number).
JavaScript is dynamically typed. A binding can hold a value of one type and later a value of another type:
let x = "Hello"; // typeof x is a string
x = 5; // changes typeof x to a number
The + operator concatenates when either operand becomes a string. Other arithmetic operators convert string operands to numbers:
const numericAddition = 5 + 7; // 12
const appendDigit = 5 + "7"; // "57"
const prependDigit = "5" + 7; // "57"
const numericSubtraction = 5 - 7; // -2
const convertedRight = 5 - "7"; // -2
const convertedLeft = "5" - 7; // -2
const invalidSubtraction = 5 - "x"; // NaN
Subtracting a nonnumeric string does not throw; it produces NaN:
"Hello" - "Dolly"; // NaN
Prefer explicit conversions such as Number(value) and String(value) at input boundaries. This makes the intended behavior visible and gives validation code a clear place to reject NaN.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents