Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript have the concept of l-value and r-value?

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:

  1. Does JavaScript also have the concept of l-value and r-value as C?

  2. 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?

like image 576
leslie.zhang Avatar asked Oct 20 '22 09:10

leslie.zhang


1 Answers

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
like image 82
Ja͢ck Avatar answered Oct 22 '22 00:10

Ja͢ck