Why is string number addition not coalescing intuitively

Viewed 68

Why is the last operation returning 20?

console.log(2 + 2); // equals 4
console.log("2" + "2"); // equals "22"
console.log(2 + 2 - 2); // equals 2
console.log("2" + "2" - "2"); // equals 20

2 Answers

+ and - evaluate left-to-right. When either operand is a string, the result is concatenation. When both are numbers, the result is addition.

In contrast, - will always coerce both sides to numbers.

'2' + '2' - '2'

does

// left-to-right
('2' + '2') - '2'
// both sides are strings, so concatenate
'22' - '2'
// operator is -, so coerce both sides to numbers
22 - 2
20

The signs + and - work very differently in string concatenation. The + operator gives direct concatenation instructions on strings whereas the - operator tries to coerce the types and perform the mathematical function.

console.log("2" + "2");
console.log(typeof ("2" + "2"));

console.log("2" - "2");
console.log(typeof("2" - "2"));

Related