Last updated: Mar 2, 2024
Reading timeยท2 min
The "Invalid left-hand side in assignment" error occurs when we have a syntax error in our JavaScript code.
The most common cause is using a single equal sign instead of double or triple equals in a conditional statement.
To resolve the issue, make sure to correct any syntax errors in your code.
Uncaught ReferenceError: Invalid left-hand side in an assignment at index.js:25 SyntaxError: Invalid left-hand side in assignment at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:117:18) at ESMLoader.moduleProvider (node:internal/modules/esm/loader:459:14) at async link (node:internal/modules/esm/module_job:68:21)
Here are some examples of how the error occurs.
// โ๏ธ Invalid left-hand side in assignment if (1 =< 7) { // ๐๏ธ should be <= console.log('yes') } // โ๏ธ Error if (7 = 7) { // ๐๏ธ should be === console.log('success') } const obj = {} // โ๏ธ Error // ๐๏ธ Should be obj['background-color'] obj.background-color = "green" function sum(a,b) { return a + b; } // โ๏ธ Error sum(5, 5) = 'something' // ๐๏ธ should be const num = sum(5, 5);
The most common cause of the error is using a single equal sign =
instead of
double or triple equals when comparing values.
// โ๏ธ incorrect if (7 = 7) { // ๐๏ธ should be === console.log('success') } // โ correct if (7 === 7) { console.log('success') }
The engine interprets the single equal sign as an assignment and not as a comparison operator.
We use a single equals sign when assigning a value to a variable.
const name = 'bobby'; if (name === 'bobby') { console.log('success'); }
However, we use double equals (==) or triple equals (===) when comparing values.
Another common cause of the error is trying to set an object property that contains a hyphen using dot notation.
// โ๏ธ incorrect obj.background-color = "green" // โ correct const obj = {}; obj['background-color'] = 'green'; console.log(obj);
You should use bracket []
notation instead, e.g. obj['key'] = 'value'
.
The error also occurs when trying to assign the result of a function invocation to a value as shown in the last example.
// โ๏ธ Invalid left-hand side in assignment sum(5, 5) = 'something' // ๐๏ธ should be const num = sum(5, 5);
If you aren't sure where to start debugging, open the console in your browser or the terminal in your Node.js application and look at which line the error occurred.
The screenshot above shows that the error occurred in the index.js
file on
line 25
.
You can hover over the squiggly red line to get additional information on why the error was thrown.