ReferenceError: invalid assignment left-hand side
The issue:
This issue can happen for many reasons. The error message is self explanatory. The error basically says an unexpected assignment happened.
This error occurs due to:
- Mismatch of assignment operator
- Improper use of comparison operator
- Illegal assignment to special object
this
- etc
Lets check the examples of all the above cases:
illegal assignment to special object this
As we all know the special object this
is immutable in JavaScript. The value of this
is set by the program at runtime. But if we attempt to assign the value of speical object this
we get this error:
function getUser(){ var obj = {name: 'Joe Smith', age: 24}; this = obj; // ReferenceError: invalid assignment left-hand side } getUser();
Improper use of comparison operator
Many cases improper use of comparison operator may lead to this issue. In JavaScript the single equal is assignment and double equal is comparison operator. But if try using single equal for comparison then we get into this issue. See the code below:
var marks = 40; if (marks = 40 || marks = 50) { console.log('Improper comparison'); }
Mismatch of assignment operator
Sometimes we do mismatch of assignment operator and that leads to this issue. See the code segment below:
var name = 'Joe' += ' Smith'; console.log(name);