1

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?

4
  • 4
    What do you expect b+1 = c to mean? Commented Mar 12, 2018 at 17:28
  • assignment is right associative. Commented Mar 12, 2018 at 17:28
  • 1
    In the first case it is because you are doing b+1 = c, where c cannot be assigned to b+1. Commented Mar 12, 2018 at 17:29
  • c can be equat to 2+3, but b+1 cannot be equal to c. In other words a variable can take on a value, but a value can't take on a variable. That would be like saying 6 = 19. Commented Mar 12, 2018 at 17:31

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

it means we cannot have any operations on the left-hand side of the assignment operator. for example a +1 = 5 is not valid.
correct, if your trying to check if a+1 = 5 you would have to do 'a+1===5' as that would make it a Boolean
1

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.

Comments

0

You just need some parenthesis to make it clear what you mean:

 a = 1 + (b = c = 2+3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.