Reputation: 73
When the following code is executed in chrome console
let a, b, c;
b = 2;
a = b+1 = c = 2+3;
It says an error 'Invalid left-hand side assignment' for the last statement. But when we execute the below-given code it accepts it and does not show any error.
let a, b, c;
a = b = c = 2+3;
assignment '=' is an operator so according to operator precedence in javascript, it should work fine. what do you guys think, what is the problem?
Upvotes: 1
Views: 92
Reputation: 138257
You just need some parenthesis to make it clear what you mean:
a = 1 + (b = c = 2+3);
Upvotes: 0
Reputation: 1840
the =
operator calculate first the right side and require the left side to be lvalue.
In your second example for every assignment operator the left side is always a variable, so it works fine. but in the first example:
let a, b, c;
b = 2;
a = b+1 = c = 2+3;
you trying to assign 5 into b+1
, its simply not a variable.
Upvotes: 1
Reputation: 140
for the first code you would need to do
let a,b,c;
b=2;
a=b+1;
c=5;
doing
a=b=c=2+3
works because you arent altering a value to the left of the last equal
Upvotes: 1