Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 993
user805627 Avatar asked Dec 08 '22 21:12

user805627


1 Answers

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.

like image 190
freakish Avatar answered Dec 11 '22 11:12

freakish