-5

Why such thing would happen in Javascript?

'5'+3 = 53
'5'-3 = 2
behz4d
  • 1,819
  • 5
  • 35
  • 59

2 Answers2

3

This is happening because + operator is overloaded. If any operand is a string, string concatenation is performed. If you have two numbers, addition is performed.

In other words

2+3=5

while '2'+3='23' and 2+'3'='23'.

On the other hand, for the - operator, it is not overloaded in such a way and all operands are converted to numbers.

'8'-2=6

because - is not overloaded and operand '8' will be converted to 8. Hence, we get 6.

For further information on this, please have a look here and read the paragraphs 11.6.1 and 11.6.2.

Christos
  • 53,228
  • 8
  • 76
  • 108
1

String concatenation is done with + so Javascript will convert the first numeric 5 to a string and concatenate "5" and "3" making "53".

You cannot perform subtraction on strings, so Javascript converts the second numeric i.e. "3" to a number and subtracts 3 from 5, resulting in "2" as the result.