Guerric P
Guerric P

Reputation: 31825

Why expression as left-hand side in assignment doesn't always work?

This code works:

let foo;

(foo) = 'bar';

console.log(foo);

And that makes me believe that any expression works as a left-hand side in assignment, however, this code doesn't work:

let foo1 = "bar";
let foo2;
let foo3;
(foo1 && foo2 && foo3) = "foobar"; // The left-hand side evaluates to undefined which can't be assigned

console.log(foo1, foo2, foo3);

What makes a left-hand side valid in an assignment, why it can't always be an expression?

Upvotes: 1

Views: 1026

Answers (1)

Quentin
Quentin

Reputation: 944081

The relevant bit of the specification is here:

It is a Syntax Error if AssignmentTargetType of LeftHandSideExpression is not simple.

and here.

The simplified version is that (if we leave destructuring aside) you can assign a value to a variable or to a property of an object.

Given (foo), the parenthesis are pointless and the expression is just a variable name. This is fine.

Given (foo1 && foo2 && foo3) the values are read from the variables, compared using the && operator and the outcome is a value.

You can't assign a value to a value, only to a property or a variable.

Upvotes: 4

Related Questions