In JavaScript, if you put some kind of expression on the left side of an assignment expression, the engine will throw a ReferenceError. For example,
// 'this' on the left side
this = window; // ReferenceError: Invalid left-hand side in assignment
or
// function call expression on the left side
var a;
var fn = function() {return a};
a === fn(); // true
a = 1; // 1
fn() = 5; // ReferenceError: Invalid left-hand side in assignment
or
var a;
a = 1; // 1
(a) = 2; // 2
(1, a) = 3; // ReferenceError: Invalid left-hand side in assignment
My questions are:
Does JavaScript also have the concept of l-value and r-value as C?
Why function call expression can not appear on the left-hand of an assignment expression? In the above example, since a === fn()
, what's the difference between a = 5
and fn() = 5
. I know that ES5 spec mandates this, but why is it designed like that?
According to the specification of assignments, the following expressions are not valid as the target for an assignment:
this
Literal
ArrayLiteral
ObjectLiteral
FunctionExpression
ClassExpression
GeneratorExpression
RegularExpressionLiteral
TemplateLiteral
For example, the following assignments are invalid too:
this = "bar"; // this
"foo" = "bar"; // Literal
/foo/ = "bar"; // RegularExpressionLiteral
["foo"] = "bar"; // ArrayLiteral
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With