MSX
MSX

Reputation: 359

JavaScript assignment changes the addition operation semantics?

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"?

Upvotes: 6

Views: 85

Answers (1)

zzzzBov
zzzzBov

Reputation: 179176

{} + 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.

Upvotes: 7

Related Questions