Solve - Invalid left-hand side in assignment Error in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Tamara Bellis

Solve - Invalid left-hand side in assignment Error #

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 solve this, make sure to correct any syntax errors in your code.

invalid left hand side in assignment error

Here are some common examples where the error occurs.

index.js
// โ›”๏ธ Invalid left-hand side in assignment if (1 =< 7) { // ๐Ÿ‘‰๏ธ should be <= console.log('yes') } // โ›”๏ธ Invalid left-hand side in assignment if (7 = 7) { // ๐Ÿ‘‰๏ธ should be === console.log('success') } const obj = {} // โ›”๏ธ Invalid left-hand side in assignment // ๐Ÿ‘‡๏ธ Should be obj['background-color'] obj.background-color = "green" function sum(a,b) { return a + b; } // โ›”๏ธ Invalid left-hand side in assignment 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.

The engine interprets the single equal sign as assignment and not as comparison operator.

Another common cause of the error is trying to set an object property that includes a hyphen using dot notation. 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.

If you're not sure where to start debugging, open the console in your browser or the terminal in your Node.js application and look on which line the error occurred.

invalid left hand side in assignment error

The screenshot above shows that the error occurred in the index.js file on line 25.

You can paste your code into an online Syntax Validator. The validator should be able to tell you on which line the error occurs.

You can hover over the squiggly red line to get additional information on why the error was thrown.

To solve the "Invalid left-hand side in assignment" error make sure to correct any syntax errors in your code.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee