Addition in Javascript is really amazing.
In Chrome and Firefox, {} + 1
equals number 1; but in Node.js, {} + 1
equals string '[object Object]1'. On other hand, 1 + {}
equals '1[object Object]' in both browsers and Node.js.
Who can explain why {} + 1
equals 1 in the browsers?
This a bit complicated. This happens, because most JavaScript engines interpret {}
as a code block, not object. Thus {}+1
is essentially the same as +1
. If you do (for example)
({}+1})
then the code inside brackets ()
will be interpreted as a expression, not code block. Thus {}
becomes an actual object.
Read this for more details:
http://www.2ality.com/2012/01/object-plus-object.html
The article also explains why it is different in Node.Js.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With