Why does `{} + 1` get number 1 in Chrome and Firefox, but the string '[object Object] 1' in Node.js?

The addition to Javascript is really awesome.
In Chrome and Firefox, {} + 1 equals the number 1; but in Node.js, {} + 1 is string '[object Object] 1'. On the other hand, 1 + {} is equal to '1 [object Object]' in both browsers and Node.js.
Who can explain why {} + 1 is 1 in browsers?

+4
source share
1 answer

This is a bit complicated. This happens because most JavaScript engines interpret {} as a code block, not an object. So {}+1 is essentially the same as +1 . If you do (for example)

 ({}+1}) 

then the code inside the brackets () will be interpreted as an expression, not a block of code. Thus, {} becomes the 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 from Node.Js.

+14
source

Source: https://habr.com/ru/post/1432277/


All Articles