Yogita088 Yogita088 - 7 months ago 14
Javascript Question

Why does Javascript's console.log subtracts with - sign and concats with + sign?

So, here is the thing

console.log('2' - '1')
prints 1 which is expected as the strings are converted to numbers and operated on - sign. But when
console.log('2' + '1')
is executed it prints 21 which is concatenation.Can someone explain what's the reasoning behind this behaviour ?


If you have two strings, you can concatenate them with +. This is not uncommon, many languages do that.

There is no - operator for strings. So when you use it, it reverts back to the existing - operator, which only works for numbers. And Javascript is trying to be helpful by converting the strings to numbers automatically. That is not as common, but it seems you expected it, so no surprise here.

If you want to convert a string (or something that might be a string) to a number, you can use +x. You need to convert both, because if either is a string, you get concatenation.

console.log( (+'2') + (+'1') );  // logs 3