How to fix SyntaxError - 'invalid assignment left-hand side in JavaScript'?
Last Updated :
06 Aug, 2024
In JavaScript, a SyntaxError : Invalid Assignment Left-Hand Side
occurs when the interpreter encounters an invalid expression or structure on the left side of an assignment operator (=
).
This error typically arises when trying to assign a value to something that cannot be assigned, such as literals, expressions, or the result of function calls. Let’s explore this error in more detail and see how to resolve it with some examples.
Understanding an error
An invalid assignment left-hand side error occurs when the syntax of the assignment statement violates JavaScript's rules for valid left-hand side expressions. The left-hand side should be a target that can receive an assignment like a variable, object property or any array element, let's see some cases where this error can occur and also how to resolve this error.
Case 1: Error Cause: Assigning to Literals
When you attempt to assign a value to a literal like a number, string or boolean it will result in SyntaxError: Invalid Assignment Left-Hand Side.
Example:
5 = x;
Output
SyntaxError: invalid assignment left-hand side
Resolution of error
In this case values should be assigned to variables or expressions which will be on the left side of an equation and avoid assigning values directly to literals.
JavaScript
let x = 5;
console.log(x);
Output
5
Case 2: Error Cause: Assigning to Function Calls
Assigning a value directly to the result of function call will give an invalid assignment left-hand side error.
Example:
function getX() {
return 10;
}
getX() = x;
Output
SyntaxError: Invalid assignment left-hand side
Explanation: In this example, getX()
returns a value but is not a valid target for assignment. Assignments should be made to variables, object properties, or array elements, not to the result of a function call.
Resolution of error
Therefore, store it into a variable or at least place it on the left-hand side that is valid for assignment.
JavaScript
function getX() {
return 10;
}
let x = getX();
console.log(x);
Output
10