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 betweena = 5
andfn() = 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:
For example, the following assignments are invalid too: