Why does "5" + 3 give "53" but "5" - 3 give 2?
The + operator does string concatenation if either side is a string, so 3 becomes "3". The -, * and / operators only work on numbers, so they convert "5" to 5 first.
Explain it simply
The + sign has two jobs in JavaScript: adding numbers and joining strings. When it sees a string on either side, it picks the joining job and turns the other side into a string.
The -, *, / and % signs have only one job: maths. So they convert both sides to numbers first. If the conversion fails, you get NaN.
Expressions are evaluated left to right, which matters when you mix types.
Example
console.log("5" + 3); // Output: 53
console.log("5" - 3); // Output: 2
console.log("5" * "2"); // Output: 10
console.log(true + 1); // Output: 2
console.log(3 + 4 + "5"); // Output: 75
console.log("3" + 4 + 5); // Output: 345
console.log(typeof ("5" + 3)); // Output: string
console.log(+"42" + 1); // Output: 43Walk through 3 + 4 + "5": first 3 + 4 is 7 (both numbers), then 7 + "5" is "75". In "3" + 4 + 5, the first step is already a string, so everything after is joined.
The unary + in +"42" is a short way to convert a string to a number.
What to say in the interview
"Binary + concatenates if either operand is a string after converting objects to primitives; otherwise it adds numbers. The other arithmetic operators always convert to numbers. Evaluation is left to right, so 3 + 4 + '5' is '75' but '3' + 4 + 5 is '345'. In real code I convert explicitly with Number() so input from a form doesn't get concatenated by accident."
Common mistakes
- Adding values read from
input.value(always strings) and getting"1020"instead of30.