Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript assignment changes the addition operation semantics?

Tags:

javascript

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

Why does the assignment change the semantics of the right-hand side expression? Shouldn't the right-hand side expression be "context-free"?

like image 887
MSX Avatar asked Oct 09 '13 19:10

MSX


1 Answers

{} + 1

is interpreted as a code block followed by +1, which evaluates to 1. OTOH:

x = {} + 1

is evaluated as new Object() plus 1

If you change your original statement to:

new Object() + 1

You will see "[object Object]1" as a result.

like image 59
zzzzBov Avatar answered Nov 07 '22 10:11

zzzzBov