Invalid left-hand side in assignment in JavaScript [Solved]
Last updated: Mar 2, 2024 Reading time · 2 min
# Invalid left-hand side in assignment in JavaScript [Solved]
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.
Here are some examples of how the error occurs.
# Use double or triple equals when comparing values
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 an assignment and not as a comparison operator.
We use a single equals sign when assigning a value to a variable.
However, we use double equals (==) or triple equals (===) when comparing values.
# Use bracket notation for object properties that contain hyphens
Another common cause of the error is trying to set an object property that contains a hyphen using dot notation.
You should use bracket [] notation instead, e.g. obj['key'] = 'value' .
# Assigning the result of calling a function to a 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 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.
Borislav Hadzhiev
Web Developer
Copyright © 2024 Borislav Hadzhiev
- JS Tutorial
- JS Exercise
- JS Interview Questions
- JS Operator
- JS Projects
- JS Examples
- JS Free JS Course
- JS A to Z Guide
- JS Formatter
JavaScript ReferenceError – Invalid assignment left-hand side
This JavaScript exception invalid assignment left-hand side occurs if there is a wrong assignment somewhere in code. A single “=” sign instead of “==” or “===” is an Invalid assignment.
Error Type:
Cause of the error: There may be a misunderstanding between the assignment operator and a comparison operator.
Basic Example of ReferenceError – Invalid assignment left-hand side, run the code and check the console
Example 1: In this example, “=” operator is misused as “==”, So the error occurred.
Example 2: In this example, the + operator is used with the declaration, So the error has not occurred.
Output:
Similar Reads
- JavaScript Error Object Complete Reference Error objects are arising at runtime errors. The error object also uses as the base object for the exceptions defined by the user. The complete list of JavaScript Error Object properties are listed below: Error types JavaScript RangeError – Invalid dateJavaScript RangeError – Repeat count must be no 3 min read
JS Range Error
- JavaScript RangeError - Invalid date This JavaScript exception invalid date occurs if the string that has been provided to Date or Date.parse() is not valid. Message: RangeError: invalid date (Edge)RangeError: invalid date (Firefox)RangeError: invalid time value (Chrome)RangeError: Provided date is not in valid range (Chrome)Error Type 2 min read
- JavaScript RangeError - Repeat count must be non-negative This JavaScript exception repeat count must be non-negative occurs if the argument passed to String.prototype.repeat() method is a negative number. Message: RangeError: argument out of range RangeError: repeat count must be non-negative (Firefox) RangeError: Invalid count value (Chrome) Error Type: 1 min read
JS Reference Error
- JavaScript ReferenceError - Can't access lexical declaration`variable' before initialization This JavaScript exception can't access the lexical declaration `variable' before initialization occurs if a lexical variable has been accessed before initialization. This could happen inside any block statement when let or const declarations are accessed when they are undefined. Message: ReferenceEr 2 min read
- JavaScript ReferenceError - Invalid assignment left-hand side This JavaScript exception invalid assignment left-hand side occurs if there is a wrong assignment somewhere in code. A single “=” sign instead of “==” or “===” is an Invalid assignment. Message: ReferenceError: invalid assignment left-hand side Error Type: ReferenceError Cause of the error: There ma 2 min read
- JavaScript ReferenceError - Assignment to undeclared variable This JavaScript exception Assignment to undeclared variable occurs in strict-mode If the value has been assigned to an undeclared variable. Message: ReferenceError: assignment to undeclared variable "x" (Firefox) ReferenceError: "x" is not defined (Chrome) ReferenceError: Variable undefined in stric 2 min read
- JavaScript ReferenceError - Reference to undefined property "x" This JavaScript warning reference to undefined property occurs if a script tries to access an object property that doesn't exist. Message: ReferenceError: reference to undefined property "x" (Firefox)Error Type: ReferenceError(Only reported by firefox browser)Cause of the error: The script is trying 2 min read
- JavaScript ReferenceError - variable is not defined This JavaScript exception variable is not defined and occurs if there is a non-existent variable that is referenced somewhere. Message: ReferenceError: "x" is not defined Error Type: ReferenceError Cause of Error: There is a non-existent variable that is referenced somewhere in the script. That vari 1 min read
- JavaScript ReferenceError Deprecated caller or arguments usage This JavaScript exception deprecated caller or arguments usage occurs only in strict mode. It occurs if any of the Function.caller or Function.arguments properties are used, Which are depreciated. Message: TypeError: 'arguments', 'callee' and 'caller' are restricted function properties and cannot be 1 min read
JS Syntax Error
- JavaScript SyntaxError - Illegal character This JavaScript exception illegal character occurs if there is an invalid or unexpected token that doesn't belong there in the code. Understanding an errorAn "Unexpected token ILLEGAL" error signifies that there is an invalid character present within the code, in certain situations, JavaScript requi 2 min read
- JavaScript SyntaxError - Identifier starts immediately after numeric literal This JavaScript exception identifier starts immediately after a numeric literal occurs if an identifier starts with a number. Message: SyntaxError: Unexpected identifier after numeric literal (Edge) SyntaxError: identifier starts immediately after numeric literal (Firefox) SyntaxError: Unexpected nu 1 min read
- JavaScript SyntaxError - Function statement requires a name This JavaScript exception function statement requires a name that occurs if there is any function statement in the script which requires a name. Message: Syntax Error: Expected identifier (Edge) SyntaxError: function statement requires a name [Firefox] SyntaxError: Unexpected token ( [Chrome] Error 1 min read
- JavaScript SyntaxError - Missing } after function body This JavaScript exception missing } after function body occurs if there is any syntactic mistyping while creating a function somewhere in the code. Closing curly brackets/parentheses must be incorrect order. Message: SyntaxError: Expected '}' (Edge) SyntaxError: missing } after function body (Firefo 1 min read
- JavaScript SyntaxError - Missing } after property list This JavaScript exception missing } after property list occurs if there is a missing comma, or curly bracket in the object initializer syntax. Message: SyntaxError: Expected '}' (Edge) SyntaxError: missing } after property list (Firefox) Error Type: SyntaxError Cause of Error: Somewhere in the scrip 1 min read
- JavaScript SyntaxError - Missing variable name This JavaScript exception missing variable name occurs frequently If the name is missing or the comma is wrongly placed. There may be a typing mistake. Message: SyntaxError: missing variable name (Firefox)SyntaxError: Unexpected token = (Chrome)Error Type: SyntaxErrorCause of Error: There might be a 2 min read
- JavaScript SyntaxError - Missing ] after element list This JavaScript exception missing ] after element list occurs, It might be an error in array initialization syntax in code. Missing closing bracket (“]”) or a comma (“,”) also raises an error. Message: SyntaxError: missing ] after element listError Type: SyntaxErrorCause of Error: Somewhere in the s 2 min read
- JavaScript SyntaxError - Invalid regular expression flag "x" This JavaScript exception invalid regular expression flag occurs if the flags, written after the second slash in RegExp literal, are not from either of (g, i, m, s, u, or y). Error Message on console: SyntaxError: Syntax error in regular expression (Edge) SyntaxError: invalid regular expression flag 1 min read
- JavaScript SyntaxError "variable" is a reserved identifier This JavaScript exception variable is a reserved identifier occurs if the reserved keywords are used as identifiers. Message: SyntaxError: The use of a future reserved word for an identifier is invalid (Edge) SyntaxError: "x" is a reserved identifier (Firefox) SyntaxError: Unexpected reserved word ( 1 min read
- JavaScript SyntaxError - Missing ':' after property id This JavaScript exception missing : after property id occurs if objects are declared using the object's initialization syntax. Message: SyntaxError: Expected ':' (Edge)SyntaxError: missing : after property id (Firefox)Error Type: SyntaxErrorCause of Error: Somewhere in the code, Objects are created 2 min read
- JavaScript SyntaxError - Missing ) after condition This JavaScript exception missing ) after condition occurs if there is something wrong with if condition. Parenthesis should be after the if keyword. Message: SyntaxError: Expected ')' (Edge)SyntaxError: missing ) after condition (Firefox)Error Type: SyntaxErrorCause of Error: Somewhere in the code 2 min read
- JavaScript SyntaxError - Missing formal parameter This JavaScript exception missing formal parameter occurs if any function declaration doesn't have the valid parameters. Message: SyntaxError: missing formal parameter (Firefox)Error Type: SyntaxErrorCause of Error: The function declaration is missing the formal parameters. Case 1: Incorrect Functio 2 min read
- JavaScript SyntaxError - Missing ; before statement This JavaScript exception missing ; before statement occurs if there is a semicolon (;) missing in the script. Message: SyntaxError: Expected ';' (Edge) SyntaxError: missing ; before statement (Firefox) Error Type: SyntaxError Cause of Error: Somewhere in the code, there is a missing semicolon (;). 1 min read
- JavaScript SyntaxError - Missing = in const declaration This JavaScript exception missing = in const declaration occurs if a const is declared and value is not provided(like const ABC_DEF;). Need to provide the value in same statement (const ABC_DEF = '#ee0'). Message: SyntaxError: Const must be initialized (Edge) SyntaxError: missing = in const declarat 1 min read
- JavaScript SyntaxError - Missing name after . operator This JavaScript exception missing name after . operator occurs if the dot operator (.) is used in the wrong manner for property access. Message: SyntaxError: missing name after . operator Error Type: SyntaxError Cause of Error: The dot operator (.) is used to access the property. Users will have to 1 min read
- JavaScript SyntaxError - Redeclaration of formal parameter "x" This JavaScript exception redeclaration of formal parameter occurs if a variable name is a function parameter and also declared again inside the function body using a let assignment. Message: SyntaxError: Let/Const redeclaration (Edge) SyntaxError: redeclaration of formal parameter "x" (Firefox) Syn 1 min read
- JavaScript SyntaxError - Missing ) after argument list This JavaScript exception missing ) after argument list occurs if there is an error in function calls. This could be a typing mistake, a missing operator, or an unescaped string. Message: SyntaxError: Expected ')' (Edge) SyntaxError: missing ) after argument list (Firefox) Error Type: SyntaxError Ca 1 min read
- JavaScript SyntaxError - Return not in function This JavaScript exception return (or yield) not in function occurs if a return/yield statement is written outside the body of the function. Message: SyntaxError: 'return' statement outside of function (Edge)SyntaxError: return not in function (Firefox)SyntaxError: yield not in function (Firefox)Erro 2 min read
- JavaScript SyntaxError: Unterminated string literal This JavaScript error unterminated string literal occurs if there is a string that is not terminated properly. String literals must be enclosed by single (') or double (") quotes. Message:SyntaxError: Unterminated string constant (Edge)SyntaxError: unterminated string literal (Firefox)Error Type:Syn 2 min read
- JavaScript SyntaxError - Applying the 'delete' operator to an unqualified name is deprecated This JavaScript exception applying the 'delete' operator to an unqualified name is deprecated works in strict mode and it occurs if variables are tried to be deleted with the delete operator. Message: SyntaxError: Calling delete on expression not allowed in strict mode (Edge) SyntaxError: applying t 1 min read
- JavaScript SyntaxError - Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead This JavaScript warning Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead occurs if there is a source map syntax defined in a JavaScript source, Which has been depreciated. Message: Warning: SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead Warn 1 min read
- JavaScript SyntaxError - Malformed formal parameter This JavaScript exception malformed formal parameter occurs if the argument list of a Function() constructor call is not valid. Message: SyntaxError: Expected {x} (Edge)SyntaxError: malformed formal parameter (Firefox)Error Type: SyntaxErrorCause of Error: The argument list passed to the function is 2 min read
- JavaScript SyntaxError - "0"-prefixed octal literals and octal escape sequences are deprecated This JavaScript exception 0-prefixed octal literals and octal escape sequences are deprecated works in strict mode only. For octal literals, the "0o" prefix can be used instead. Message: SyntaxError: Octal numeric literals and escape characters not allowed in strict mode (Edge) SyntaxError: "0"-pref 1 min read
- JavaScript SyntaxError - Test for equality (==) mistyped as assignment (=)? This JavaScript warning test for equality (==) is mistyped as an assignment (=)? occurs if by assignment (=) is used in place of equality (==). Message: Warning: SyntaxError: test for equality (==) mistyped as assignment (=)? Error Type: SyntaxError: Warning which is reported only if javascript.opti 1 min read
- JavaScript SyntaxError - "x" is not a legal ECMA-262 octal constant This JavaScript warning 08 (or 09) is not a legal ECMA-262 octal constant that occurs if the literals 08 or 09 are used as a number. This occurs because these literals cannot be treated as an octal number. Message: Warning: SyntaxError: 08 is not a legal ECMA-262 octal constant. Warning: SyntaxError 1 min read
JS Type Error
- JavaScript TypeError - "X" is not a non-null object This JavaScript exception is not a non-null object that occurs if an object is not passed where it is expected. So the null is passed which is not an object and it will not work. Message: TypeError: Invalid descriptor for property {x} (Edge) TypeError: "x" is not a non-null object (Firefox) TypeErro 1 min read
- JavaScript TypeError - "X" is not a constructor This JavaScript exception is not a constructor that occurs if the code tries to use an object or a variable as a constructor, which is not a constructor. Message: TypeError: Object doesn't support this action (Edge) TypeError: "x" is not a constructor TypeError: Math is not a constructor TypeError: 1 min read
- JavaScript TypeError - "X" has no properties This JavaScript exception null (or undefined) has no properties that occur if there is an attempt to access properties of null and undefined. They don't have any such properties. Message: TypeError: Unable to get property {x} of undefined or null reference (Edge) TypeError: null has no properties (F 1 min read
- JavaScript TypeError - "X" is (not) "Y" This JavaScript exception X is (not) Y occurs if there is a data type that is not expected there. Unexpected is undefined or null values. Message: TypeError: Unable to get property {x} of undefined or null reference (Edge) TypeError: "x" is (not) "y" (Firefox) Few example are given below: TypeError: 1 min read
- JavaScript TypeError - "X" is not a function This JavaScript exception is not a function that occurs if someone trying to call a value from a function, but in reality, the value is not a function. Message: TypeError: Object doesn't support property or method {x} (Edge) TypeError: "x" is not a function Error Type: TypeError Cause of Error: Ther 1 min read
- JavaScript TypeError - 'X' is not iterable This JavaScript exception is not iterable occurs if the value present at the right-hand-side of for…of or as argument of a function such as Promise.all or TypedArray.from, can not be iterated or is not an iterable object. Message: TypeError: 'x' is not iterable (Firefox, Chrome) TypeError: 'x' is no 1 min read
- JavaScript TypeError - More arguments needed This JavaScript exception more arguments needed occurs if there is an error in the way of function is called. If a few arguments are provided then more arguments need to be provided. Message: TypeError: argument is not an Object and is not null (Edge) TypeError: Object.create requires at least 1 arg 1 min read
- JavaScript TypeError - "X" is read-only This JavaScript exception is read-only works in strict mode-only and It occurs if a global variable or object property which has assigned to a value, is a read-only property. Message: TypeError: Assignment to read-only properties is not allowed in strict mode (Edge) TypeError: "x" is read-only (Fire 1 min read
- JavaScript TypeError - Reduce of empty array with no initial value This JavaScript exception reduce of empty array with no initial value occurs if a reduce function is used with the empty array. Message: TypeError: reduce of empty array with no initial value Error Type: TypeError Cause of Error: This error is raised if an empty array is provided to the reduce() met 1 min read
- JavaScript TypeError - Can't assign to property "X" on "Y": not an object This JavaScript exception can't assign to property occurs in strict-mode only and this error occurs If the user tries to create a property on any of the primitive values like a symbol, a string, a number, or a boolean. Primitive values cannot be used to hold any property. Message: TypeError: can't a 1 min read
- JavaScript TypeError - Can't access property "X" of "Y" This JavaScript exception can't access property occurs if property access was performed on undefined or null values. Message: TypeError: Unable to get property {x} of undefined or null reference (Edge) TypeError: can't access property {x} of {y} (Firefox) TypeError: {y} is undefined, can't access pr 1 min read
- JavaScript TypeError - Can't define property "X": "Obj" is not extensible This JavaScript exception can't define property "x": "obj" is not extensible occurs when Object.preventExtensions() is used on an object to make it no longer extensible, So now, New properties can not be added to the object. Message: TypeError: Cannot create property for a non-extensible object (Edg 1 min read
- JavaScript TypeError - X.prototype.y called on incompatible type This JavaScript exception called on incompatible target (or object)" occurs if a function (on a given object), is called with a 'this' corresponding to a different type other than the type expected by the function. Message: TypeError: 'this' is not a Set object (EdgE) TypeError: Function.prototype.t 1 min read
- JavaScript TypeError - Invalid assignment to const "X" This JavaScript exception invalid assignment to const occurs if a user tries to change a constant value. Const declarations in JavaScript can not be re-assigned or re-declared. Message: TypeError: invalid assignment to const "x" (Firefox) TypeError: Assignment to constant variable. (Chrome) TypeErro 1 min read
- JavaScript TypeError - Property "X" is non-configurable and can't be deleted This JavaScript exception property is non-configurable and can't be deleted if the user tries to delete a property, and the property is non-configurable. Message: TypeError: Calling delete on 'x' is not allowed in strict mode (Edge) TypeError: property "x" is non-configurable and can't be deleted. ( 1 min read
- JavaScript TypeError - Can't redefine non-configurable property "x" This JavaScript exception can't redefine non-configurable property occurs if user tries to redefine a property, but that property is non-configurable. Message: TypeError: Cannot modify non-writable property {x} (Edge) TypeError: can't redefine non-configurable property "x" (Firefox) TypeError: Canno 1 min read
- JavaScript TypeError - Variable "x" redeclares argument This JavaScript exception variable redeclares argument occurs in strict-mode only and if the variable name which is also function parameter has been redeclared with the var keyword. Message: TypeError: variable "x" redeclares argument (Firefox) Error Type: TypeError Cause of the Error: A variable wh 1 min read
- JavaScript TypeError - Setting getter-only property "x" This JavaScript exception setting getter-only property works in strict-mode only and occurs if the user tries to set a new value to a property for which only a getter is specified. Message: TypeError: Assignment to read-only properties is not allowed in strict mode (Edge) TypeError: setting getter-o 2 min read
- JavaScript TypeError - Invalid 'instanceof' operand 'x' This JavaScript exception invalid 'instanceof' operand occurs if the right operand of the instanceof operator can not be used with a constructor object. It is an object that contains a prototype property and can be called. Message: TypeError: invalid 'instanceof' operand "x" (Firefox) TypeError: "x" 1 min read
- JavaScript TypeError - Invalid Array.prototype.sort argument This JavaScript exception invalid Array.prototype.sort argument occurs if the parameter of Array.prototype.sort() is not from either undefined or a function which sorts accordingly. Message: TypeError: argument is not a function object (Edge) TypeError: invalid Array.prototype.sort argument (Firefox 1 min read
- JavaScript TypeError - Cyclic object value This JavaScript exception cyclic object value occurs if the references of objects were found in JSON. JSON.stringify() fails to solve them. Message: TypeError: cyclic object value (Firefox) TypeError: Converting circular structure to JSON (Chrome and Opera) TypeError: Circular reference in value arg 1 min read
- JavaScript TypeError - Can't delete non-configurable array element This JavaScript exception can't delete non-configurable array element that occurs if there is an attempt to short array-length, and any one of the array's elements is non-configurable. Message: TypeError: can't delete non-configurable array element (Firefox) TypeError: Cannot delete property '2' of 1 min read
JS Other Errors
- JavaScript URIError | Malformed URI Sequence This JavaScript exception malformed URI sequence occurs if the encoding or decoding of URI is unsuccessful. Message: URIError: The URI to be encoded contains invalid character (Edge) URIError: malformed URI sequence (Firefox) URIError: URI malformed (Chrome) Error Type: URIError Cause of the Error: 1 min read
- JavaScript Warning - Date.prototype.toLocaleFormat is deprecated This JavaScript warning Date.prototype.toLocaleFormat is deprecated; consider using Intl.DateTimeFormat instead occurs if user is using the non-standard Date.prototype.toLocaleFormat method. Message: Warning: Date.prototype.toLocaleFormat is deprecated; consider using Intl.DateTimeFormat instead Err 1 min read
- Logging Script Errors in JavaScript In this article, we will learn to log script Errors using JavaScript. It is useful in case where scripts from any other source run/executes under the website (Ex - in an iframe) or cases where any of your viewer makes use of Browser's Console trying to alter the script or you want to monitor your JS 6 min read
JS Error Instance
- JavaScript Error message Property In JavaScript error message property is used to set or return the error message. Syntax: errorObj.message Return Value: It returns a string, representing the details of the error. More example codes for the above property are as follows: Below is the example of the Error message property. Example 1: 1 min read
- JavaScript Error name Property In JavaScript, the Error name property is used to set or return the name of an error. Syntax: errorObj.name Property values: This property contains six different values as described below: SyntaxError: It represents a syntax error.RangeError: It represents an error in the range.ReferenceError: It re 2 min read
- JavaScript Error.prototype.toString() Method The Error.prototype.toString() method is an inbuilt method in JavaScript that is used to return a string representing the specified Error object. Syntax: e.toString() Parameters: This method does not accept any parameters. Return value: This method returns a string representing the specified Error o 1 min read
- Web Technologies
- JavaScript-Errors
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
Fixing Assignment Errors in JavaScript: 'Invalid left-hand side'
Error message.
- "Invalid assignment left-hand side"
What it Means
This error arises in JavaScript when you attempt to assign a value to something that cannot be assigned to. In simpler terms, you're trying to put data (the value on the right side of the equal sign) into a location (the left side of the equal sign) that doesn't accept it.
Common Causes
Here are some frequent scenarios that lead to this error:
- You might accidentally use a single equal sign ( = ) instead of a comparison operator (like == or === ) within an if statement or similar conditional block.
- For example: if (x = 5 ) { // Incorrect - trying to assign within an if statement console .log( "This won't work" ); }
- The correct way to compare would be: if (x === 5 ) { // Correct - using comparison operator console .log( "This works" ); }
Assigning to Read-Only Values
- JavaScript has certain built-in values or properties that cannot be changed directly. Trying to assign to these will trigger the error.
- The result of functions like document.getElementById() , which returns an element reference (you can modify the element's content using properties like innerHTML ).
- Constants declared with const .
Incorrect Object Property Access
- If you attempt to assign to a non-existent property of an object, JavaScript might throw this error. Ensure the property exists before assignment.
Fixing the Error
Double-Check Comparisons
- Verify that you're using the correct operators ( == , === , != , etc.) for comparisons within conditional statements.
Avoid Assigning to Read-Only Values
- If you need to modify a read-only value, consider alternative approaches. For example, create a new variable or use a property like innerHTML to change the content of an element.
Verify Object Properties
- Before assigning to an object property, make sure the property exists. You can use the in operator or access it conditionally (e.g., if (obj.hasOwnProperty('property')) ).
Related Errors
- TypeError: Cannot set property 'x' of undefined This arises when you try to assign to a property of an undefined variable or object. Ensure the variable or object exists before accessing its properties.
- ReferenceError: Invalid left-hand side in assignment This error might appear in similar scenarios, often when you attempt to assign to a variable that hasn't been declared or is inaccessible. Double-check variable declarations and scope.
Troubleshooting Tips
- Use Browser Developer Tools When you encounter these errors, inspect your code using your browser's developer tools (usually F12 key). The console will pinpoint the exact line causing the issue, making debugging easier.
- Read Error Messages Carefully Error messages often provide valuable clues about the source of the problem. Pay attention to the line number mentioned in the error and the specific details it reveals.
- Break Down Complex Code If you're working with intricate logic, try breaking it down into smaller, more manageable chunks. This can help isolate the part where the invalid assignment is occurring.
- Console Logging for Debugging Strategically place console.log statements throughout your code to inspect variable values and the flow of your program. This can aid in visualizing the state of your variables at different points.
- Consider Linting Tools Tools like ESLint or JSHint can help you identify potential errors and enforce code style guidelines, which might catch these issues early on.
- Asynchronous Code When dealing with asynchronous code (like using promises or callbacks), be cautious about assigning values before they're available. Understand the timing and flow of your asynchronous operations.
- Strict vs. Non-Strict Mode JavaScript has strict mode, which enforces stricter rules on variable declarations and other aspects. Some errors you might encounter in non-strict mode might become SyntaxErrors in strict mode.
A. document.getElementById Result
Understand the Error The error signifies that you're trying to assign a value to something that can't be assigned to. This could be due to various reasons, as explained earlier.
Identify the Cause Analyze your code to determine why the assignment is invalid. Refer to the related example codes to see if your situation matches any of them.
Fix the Issue Depending on the cause, you might need to:
- Use comparison operators If you're accidentally using an assignment operator ( = ) in a conditional statement, use the correct comparison operator (like == , === , != , etc.).
- Avoid read-only assignments If you're trying to modify a read-only value (like document.getElementById result or a const variable), consider alternative approaches (e.g., modify element content using properties like innerHTML or declare a new variable).
- Ensure object properties exist If you're assigning to a non-existent property of an object, check if the property exists before assigning.
Imagine the "Invalid assignment left-hand side" error as a warning sign. It's pointing out a potential problem in your code. By addressing this issue, you'll end up with code that works as intended.
"Errors: Not a constructor" is a common error you might encounter in JavaScript when you try to create a new object using the new keyword with something that's not actually designed to be a constructor function
"Errors: Invalid date" is a common error you might encounter in JavaScript code when you try to work with dates but provide invalid data
"Errors: Not a function" indicates that JavaScript encountered an attempt to call something as a function, but it wasn't actually a function
In JavaScript, a semicolon ( ; ) acts as a statement terminator. It tells the JavaScript engine (the program that interprets your code) that a particular instruction has ended
"Errors: is not iterable" indicates that you're trying to use a loop or other construct that expects a sequence of values (iterable) on something that JavaScript can't iterate over
This error occurs specifically when you're using JavaScript's strict mode. Strict mode is a special mode that enforces stricter coding practices
"Errors: Missing initializer in const"What it MeansThis error occurs when you declare a variable using the const keyword (used for constants) but don't assign a value to it at the same time
Demystifying JavaScript‘s "Invalid Assignment Left-Hand Side" Error
Assignment operations are fundamental in JavaScript – we use them all the time to assign values to variables. However, occasionally you may come across a confusing error:
This "Invalid Assignment Left-Hand Side" error occurs when you try to assign a value to something that JavaScript will not allow. At first glance, this doesn‘t seem to make sense – isn‘t assignment valid in JS?
In this comprehensive guide, we‘ll demystify exactly when and why this error occurs and equip you with the knowledge to resolve it.
Assignment and Equality Operators in JavaScript
To understand this error, we first need to understand the role of assignment and equality operators in JavaScript.
The Assignment Operator
The assignment operator in JS is the single equals sign = . It is used to assign a value to a variable, like so:
This stores the value 10 in the variable x . Simple enough!
The Equality Operator
The equality operator == checks if two values are equal to each other. For example:
The equality operator == is different from the assignment operator = – it compares values rather than assigning them.
Mixing up assignment and equality is a common source of bugs in JS programs.
Immutable vs Mutable Values in JavaScript
In JavaScript, some values are immutable – they cannot be changed or reassigned. The most common immutable values are:
- Constants like Math.PI
- Primitive values like undefined or null
Trying to reassign an immutable value will lead to our error.
On the other hand, mutable values like variables can be reassigned:
Keeping mutable vs immutable values in mind is key to avoiding "Invalid Assignment" errors.
When and Why This Error Occurs
There are two main situations that cause an "Invalid Assignment Left-Hand Side" error:
1. Attempting to Mutate an Immutable Constant
Immutable constants in JavaScript cannot be reassigned. For example:
Core language constants like Math.PI are immutable. Trying to alter them with the assignment operator = will throw an error.
You‘ll also get an error trying to reassign a declared const variable:
2. Accidentally Using Assignment = Instead of Equality ==
Another common source of this error is accidentally using the single = assignment operator when you meant to use the == equality operator:
This can lead to logical errors, as you are assigning 10 to x rather than checking if x equals 10 .
According to a 2020 survey, over 40% of JavaScript developers have made this mistake that led to bugs in their code.
Example Error Message
When an invalid assignment occurs, you‘ll see an error like:
This tells us there is an invalid assignment on line 2 of myScript.js . The full error message gives us an important clue that an assignment operation is causing the issue.
Let‘s look at a full code example:
Running this would result in our error:
Now that we‘ve seen the error, let‘s walk through debugging techniques.
Debugging an Invalid Assignment
When the "Invalid Assignment Left-Hand Side" error appears, follow these steps:
- Identify the exact line causing the issue from the error stack trace
- Check if the line is trying to reassign a constant value
- If so, use a variable instead of a constant
- Otherwise, verify = is intended and not == for equality
Let‘s demonstrate with our code example:
The error said line 2 was invalid, so we examine it:
Aha! We‘re trying to assign to the constant PI . Since constants are immutable, this causes an error.
To fix, we need to use a mutable variable instead:
That‘s all there is to debugging simple cases like this. Now let‘s look at some tips to avoid the problem altogether.
Avoiding the "Invalid Assignment" Error
With knowledge of assignments and equality in JavaScript, you can avoid these errors with:
- Using const for true constants – Avoid reassignment by default
- Declaring variables rather than trying to mutate language builtins
- Take care with = vs == – Understand what each one does
- Use a linter – Catches many invalid assignments before runtime
- Improve testing – Catch assumption errors around assignments early
- Refactor code – Make invalid assignments impossible through design
Avoiding mutations and validating equality logic will steer you clear of this problem.
Why This Error Matters
At first glance, the "Invalid Assignment Left-Hand Side" error may seem minor. However, it points to flawed assumptions around assignments and equality in JavaScript that can cause major issues down the line.
That‘s why understanding this error is about more than just fixing that one line of code. It represents a milestone in solidifying your mental models around immutable values, variables, assignment and equality in JavaScript.
Making assignments consciously and validating them through linting and testing will level up your code quality and make you a more proficient JS developer.
Key Takeaways
To recap, the core takeaways around the "Invalid Assignment Left-Hand Side" error are:
- It occurs when trying to assign a value to a constant or immutable value
- Accidentally using = instead of == for equality checks is another common cause
- The error message directly states "invalid assignment" which provides a clue
- Debug by checking for assignment to constants or verifying equality checks
- Declare variables and use const properly to avoid reassignment errors
- Differentiate between = assignment and == equality checks
Learning to debug and avoid this error will improve your fundamental JavaScript skills. With time, you‘ll handle invalid assignments with ease!
Dealing with "Invalid Assignment Left-Hand Side" errors may seem cryptic initially. But by leveraging the error message itself and understanding assignments in JavaScript, you can swiftly resolve them.
Immutable values and equality logic are at the heart of these errors. With care and awareness around assignments, you can sidestep these issues in your code going forward.
Debugging and resolving errors like this are an important part of the JavaScript learning journey. Each one makes you a little wiser! So don‘t get discouraged when you run into an "Invalid Assignment" error. Leverage the techniques in this guide to level up your skills.
You maybe like,
Related posts, "what‘s the fastest way to duplicate an array in javascript".
As a fellow JavaScript developer, you may have asked yourself this same question while building an application. Copying arrays often comes up when juggling data…
1 Method: Properly Include the jQuery Library
As a JavaScript expert and editor at thelinuxcode.com, I know first-hand how frustrating the "jQuery is not defined" error can be. This single error can…
10 Awesome JavaScript Libraries You Should Try Out in 2021
JavaScript libraries are pre-written JavaScript code that help web developers tackle common tasks and challenges during development. Rather than writing everything from scratch, libraries provide…
10 Handy JavaScript Utility Functions Built with Reduce
As a JavaScript architect with over 15 years of experience, I‘ve found that many of the functional programming patterns I utilize originated decades ago. Back…
10 Hidden Gems in Chrome‘s Dev Console You Should Know
As a principal developer and coding mentor for over 15 years, I‘ve guided hundreds of aspiring engineers in mastering Chrome‘s versatile developer tools. While most…
10 More Utility Functions for Your JavaScript Toolbelt
As a JavaScript developer for over 15 years, I‘ve found that truly understanding the ins and outs of built-in methods like Array.prototype.reduce() provides the foundation…
Limited Time: Get Your Deposit Matched up to $500
- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- Remember language
- Português (do Brasil)
Destructuring assignment
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Description
The object and array literal expressions provide an easy way to create ad hoc packages of data.
The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable.
Similarly, you can destructure objects on the left-hand side of the assignment.
This capability is similar to features present in languages such as Perl and Python.
For features specific to array or object destructuring, refer to the individual examples below.
Binding and assignment
For both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern , with slightly different syntaxes.
In binding patterns, the pattern starts with a declaration keyword ( var , let , or const ). Then, each individual property must either be bound to a variable or further destructured.
All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice — once with let , once with const .
In many other syntaxes where the language binds a variable for you, you can use a binding destructuring pattern. These include:
- The looping variable of for...in for...of , and for await...of loops;
- Function parameters;
- The catch binding variable.
In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with var or let , or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.
Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.
{ a, b } = { a: 1, b: 2 } is not valid stand-alone syntax, as the { a, b } on the left-hand side is considered a block and not an object literal according to the rules of expression statements . However, ({ a, b } = { a: 1, b: 2 }) is valid, as is const { a, b } = { a: 1, b: 2 } .
If your coding style does not include trailing semicolons, the ( ... ) expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.
Note that the equivalent binding pattern of the code above is not valid syntax:
You can only use assignment patterns as the left-hand side of the assignment operator. You cannot use them with compound assignment operators such as += or *= .
Default value
Each destructured property can have a default value . The default value is used when the property is not present, or has value undefined . It is not used if the property has value null .
The default value can be any expression. It will only be evaluated when necessary.
Rest property
You can end a destructuring pattern with a rest property ...rest . This pattern will store all remaining properties of the object or array into a new object or array.
The rest property must be the last in the pattern, and must not have a trailing comma.
Array destructuring
Basic variable assignment, destructuring with more elements than the source.
In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N , only the first N variables are assigned values. The values of the remaining variables will be undefined.
Swapping variables
Two variables values can be swapped in one destructuring expression.
Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).
Parsing an array returned from a function
It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.
In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.
Ignoring some returned values
You can ignore return values that you're not interested in:
You can also ignore all returned values:
Using a binding pattern as the rest property
The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.
These binding patterns can even be nested, as long as each rest property is the last in the list.
On the other hand, object destructuring can only have an identifier as the rest property.
Unpacking values from a regular expression match
When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.
Using array destructuring on any iterable
Array destructuring calls the iterable protocol of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.
Non-iterables cannot be destructured as arrays.
Iterables are only iterated until all bindings are assigned.
The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.
Object destructuring
Basic assignment, assigning to new variable names.
A property can be unpacked from an object and assigned to a variable with a different name than the object property.
Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo .
Assigning to new variable names and providing default values
A property can be both
- Unpacked from an object and assigned to a variable with a different name.
- Assigned a default value in case the unpacked value is undefined .
Unpacking properties from objects passed as a function parameter
Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.
Consider this object, which contains information about a user.
Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value { id } indicates that the id property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.
You can define the name of the unpacked variable. Here we unpack the property named displayName , and rename it to dname for use within the function body.
Nested objects can also be unpacked. The example below shows the property fullname.firstName being unpacked into a variable called name .
Setting a function parameter's default value
Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.
Below we show a function where the default size is 'big' , default co-ordinates are x: 0, y: 0 and default radius is 25.
In the function signature for drawChart above, the destructured left-hand side has a default value of an empty object = {} .
You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. Otherwise, you need to at least supply an empty object literal.
For more information, see Default parameters > Destructured parameter with default value assignment .
Nested object and array destructuring
For of iteration and destructuring, computed object property names and destructuring.
Computed property names, like on object literals , can be used with destructuring.
Invalid JavaScript identifier as a property name
Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.
Destructuring primitive values
Object destructuring is almost equivalent to property accessing . This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.
Same as accessing properties, destructuring null or undefined throws a TypeError .
This happens even when the pattern is empty.
Combined array and object destructuring
Array and object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:
The prototype chain is looked up when the object is deconstructed
When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.
Specifications
Browser compatibility.
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
- Assignment operators
- ES6 in Depth: Destructuring on hacks.mozilla.org (2015)
How to fix SyntaxError: invalid assignment left-hand side
by Nathan Sebhastian
Posted on Jul 10, 2023
Reading time: 3 minutes
When running JavaScript code, you might encounter an error that says:
Both errors are the same, and they occured when you use the single equal = sign instead of double == or triple === equals when writing a conditional statement with multiple conditions.
Let me show you an example that causes this error and how I fix it.
How to reproduce this error
Suppose you have an if statement with two conditions that use the logical OR || operator.
You proceed to write the statement as follows:
When you run the code above, you’ll get the error:
This error occurs because you used the assignment operator with the logical OR operator.
An assignment operator doesn’t return anything ( undefined ), so using it in a logical expression is a wrong syntax.
How to fix this error
To fix this error, you need to replace the single equal = operator with the double == or triple === equals.
Here’s an example:
By replacing the assignment operator with the comparison operator, the code now runs without any error.
The double equal is used to perform loose comparison, while the triple equal performs a strict comparison. You should always use the strict comparison operator to avoid bugs in your code.
Other causes for this error
There are other kinds of code that causes this error, but the root cause is always the same: you used a single equal = when you should be using a double or triple equals.
For example, you might use the addition assignment += operator when concatenating a string:
The code above is wrong. You should use the + operator without the = operator:
Another common cause is that you assign a value to another value:
This is wrong because you can’t assign a value to another value.
You need to declare a variable using either let or const keyword, and you don’t need to wrap the variable name in quotations:
You can also see this error when you use optional chaining as the assignment target.
For example, suppose you want to add a property to an object only when the object is defined:
Here, we want to assign the age property to the person object only when the person object is defined.
But this will cause the invalid assignment left-hand side error. You need to use the old if statement to fix this:
Now the error is resolved.
The JavaScript error SyntaxError: invalid assignment left-hand side occurs when you have an invalid syntax on the left-hand side of the assignment operator.
This error usually occurs because you used the assignment operator = when you should be using comparison operators == or === .
Once you changed the operator, the error would be fixed.
I hope this tutorial helps. Happy coding!
Take your skills to the next level ⚡️
I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.
Learn more about this website
Connect with me on Twitter
Or LinkedIn
Type the keyword below and hit enter
Click to see all tutorials tagged with:
I am looking for a good examples of left/right hand side of an assignment in JS
I just read You Don’t Know Javascript: Scope and Closures chapter one. The LHS/RHS references did not totally sink in. I know I could do a search for this. There are so many coding blogs and articles out there. I decided to post here asking for recommended resources.
You assign a value to an identifier (variable). Identifier on the left, assignment operator ( = ), then the value you want to assign a unique name to on the right:
foo, bar, baz are identifiers, they are on the left of the assignment operator. They are being assigned 1, 2, and 3 respectively, and those values are on the right of the assignment operator.
There aren’t really any resources per se because that’s it, there isn’t much more to it than that.
Note the asssignment operator does not mean equality like in maths, it just uses the same symbol (in some other languages it does, but not Javascript).
Maybe I just need to reread the explanation from YDKJS: Scope & Closures “Compiler Speak” this weekend
…the type of look-up Engine performs affects the outcome of the look-up…
Actually, let’s be a little more precise. An RHS look-up is indistinguishable, for our purposes, from simply a look-up of the value of some variable, whereas the LHS look-up is trying to find the variable container itself, so that it can assign. In this way, RHS doesn’t really mean “right-hand side of an assignment” per se, it just, more accurately, means “not left-hand side”.
Being slightly glib for a moment, you could also think “RHS” instead means “retrieve his/her source (value)”, implying that RHS means “go get the value of…”.
Let’s dig into that deeper.
When I say:
console.log( a ); The reference to a is an RHS reference, because nothing is being assigned to a here. Instead, we’re looking-up to retrieve the value of a, so that the value can be passed to console.log(…).
By contrast:
a = 2; The reference to a here is an LHS reference, because we don’t actually care what the current value is, we simply want to find the variable as a target for the = 2 assignment operation…
Bear in mind he’s using his own terms here; these aren’t official concepts, he’s just using LHS and RHS to refer to an idea he’s trying to explain.
JavaScript lets you assign and reassign values to identifiers. So you can do let foo = 1 then sometime later foo = 2 .
When you do that, the engine will check if foo exists and assign/reassign if necessary. That’s what he’s calling a LHS reference; the only thing you care about is if that identifier exists, not the value.
If you use the variable, like foo + 2 , in this case he’s calling it a RHS reference, you only care about the value, you just want to check that foo has a value and what that value is.
I think that makes sense; the concept isn’t that much more complicated than what I originally wrote and I think he’s overcomplicating, or at least not being totally clear with the explanation.
No, I realise that, it’s how he’s using the terms here, I don’t think he’s being particularly clear. Yes you can have an invalid assignment left hand side, but the inverse isn’t true because it doesn’t make sense (he doesn’t suggest it is, but he uses the terms kinda as mirror images in his explanation). LHS and RHS are tems he’s using to make sense of assignment. He does this a few times throughout the books, and to be fair to him he’s always upfront about it just being a way for him to explain the concepts
These seem to be simply made-up terms that likely only make sense in the context of the author’s explanations - the javascript standard mentions the left-hand side in various grammar production rules - I don’t think the author means the same thing
I guess the better question is what real javascript concept or construct are you trying to understand - is it closures and scope? what about them specifically?
I should add there is an extremely important concept of rvalue and lvalue in C++ and C - but their importance and usage presumes a memory model that does not apply to javascript
couple discussions regarding the author’s terminology are found here
as far as I can tell the stackoverflow post and comments by torazaburo are spot-on - it’s very strange his answer has so many downvotes
I recommend you watching the Kyle Simpson’s “Advanced JavaScript” course on Pluralsight (you can google how to get 3 months free there) - https://app.pluralsight.com/library/courses/advanced-javascript/table-of-contents Scope section
Thank you @Waxaz I am currently watching “JS understanding the weird parts” on Udemy and reading the YDKJS series. I added this course to my list of courses Id like to explore.
I know it is a little bit late but I am reading YDKJS Scope & Closures now. I actually ended up here while searching LHS and RHS reference to understand them properly.
So how is it going? Have you finished YDKJS or Weird parts?
IMAGES
VIDEO
COMMENTS
Uncaught ReferenceError: Invalid left-hand side in assignment script.js:4 Why "&&" is wrong? javascript; angularjs; ecmascript-6; Share. Improve this question. ... Invalid left-hand side in assignment on javascript code. 1. Invalid Javascript left hand side in assignment. 0. Javascript ReferenceError: Invalid left-hand side in assignment ...
The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. It may be triggered when a single = sign was used instead of == or ===. ... SyntaxError: Invalid left-hand side in assignment (V8-based) SyntaxError: invalid assignment left-hand side (Firefox) SyntaxError: Left side of ...
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
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.
This JavaScript exception invalid assignment left-hand side occurs if there is a wrong assignment somewhere in code. A single "=" sign instead of "==" or "===" is an Invalid assignment. ... This JavaScript exception Assignment to undeclared variable occurs in strict-mode If the value has been assigned to an undeclared variable ...
"Invalid assignment left-hand side"What it MeansThis error arises in JavaScript when you attempt to assign a value to something that cannot be assigned to
There are two main situations that cause an "Invalid Assignment Left-Hand Side" error: 1. Attempting to Mutate an Immutable Constant. Immutable constants in JavaScript cannot be reassigned. ... assignment and equality in JavaScript. Making assignments consciously and validating them through linting and testing will level up your code quality ...
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. ... The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable. js.
SyntaxError: invalid assignment left-hand side or SyntaxError: Invalid left-hand side in assignment Both errors are the same, and they occured when you use the single equal = sign instead of double == or triple === equals when writing a conditional statement with multiple conditions.
Identifier on the left, assignment operator (=), then the value you want to assign a unique name to on the right: foo = 1 bar = 2 baz = 3 foo, bar, baz are identifiers, they are on the left of the assignment operator. They are being assigned 1, 2, and 3 respectively, and those values are on the right of the assignment operator.