Everyone knows about the basic concatenation of two strings in JavaScript:
> "Hello " + "World!" 'Hello World!'
But what happens if we use + + instead of + ? I just came across the following weird behavior:
> "Hello " + + "World!" 'Hello NaN' > "Hello " + + "" 'Hello 0'
From the above examples, it can be seen that the second line is converted to a number. Thus, by passing an object having the valueOf property as a function, the value returned by this function will be converted.
> "Hello " + + ({valueOf: function () {return 1; }}) 'Hello 1'
As expected, it shows "Hello 1" .
Why is the second line converted to Number ? Why not throw a syntax error or so?
source share