+ 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
2 ответов
+ 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
+ 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 ☺️☺️.