Does the purpose of JavaScript change the semantics of the add operation?

If you evaluate {} + 1 , you get 1 , but if you assign the same expression to a variable, say x = {} + 1 , the variable will contain the string "[object Object]1" .

Why does assignment alter the semantics of the expression on the right side? Should the right-side expression be โ€œcontext-freeโ€?

+6
source share
1 answer
 {} + 1 

interpreted as a block of code followed by +1 , which evaluates to 1 . From:

 x = {} + 1 

evaluated as new Object() plus 1

If you changed the original statement to:

 new Object() + 1 

As a result, you will see "[object Object]1" .

+7
source

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


All Articles