+ 2

I do not understand this code in JavaScript

why is it that console.log("5"-1) output 4 and yet console.log("5"+1) output 51 ,I don't just get it

30th Jul 2018, 1:57 PM
George S Mulbah II
George S Mulbah II - avatar
2 odpowiedzi
+ 4
Because the operator plus on the string usually means concatenation. The number is converted to a string and concatenated When any other arithmetic operator is applied to the string, the interpreter tries to work with it as a number
30th Jul 2018, 2:05 PM
Mishin870
Mishin870 - avatar
+ 4
Its one of the quirky behavior of Js. In this case suppose it is "a" + 1. Now interpreter will think you made a mistake instead of writing "1" you just wrote 1. So it will convert number to string and output will be a1. Hint : Never work with different data types in such cases otherwise you will get such unexpected output Hope this helps ☺️☺️.
30th Jul 2018, 2:14 PM
Meet Mehta
Meet Mehta - avatar