How to fix SyntaxError: invalid assignment left-hand side

by Nathan Sebhastian

Posted on Jul 10, 2023

Reading time: 3 minutes

invalid left hand side in assignment

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:

Invalid left-hand side in assignment in JavaScript [Solved]

avatar

Last updated: Mar 2, 2024 Reading time · 2 min

banner

# 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.

invalid left hand side in assignment error

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.

use 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.

assignment vs equality

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.

use bracket notation for object properties containing hyphens

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.

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

  • Skip to main content
  • Select language
  • Skip to search
  • ReferenceError: invalid assignment left-hand side

ReferenceError .

What went wrong?

There was an unexpected assignment somewhere. This might be due to a mismatch of a assignment operator and a comparison operator , for example. While a single " = " sign assigns a value to a variable, the " == " or " === " operators compare a value.

In the if statement, you want to use a comparison operator ("=="), and for the string concatenation, the plus ("+") operator is needed.

  • Assignment operators
  • Comparison operators

Document Tags and Contributors

  • ReferenceError
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • JavaScript basics
  • JavaScript technologies overview
  • Introduction to Object Oriented JavaScript
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Bitwise operators
  • Comma operator
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is not a legal ECMA-262 octal constant
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ; before statement
  • SyntaxError: missing ] after element list
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: variable "x" redeclares argument
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: unreachable code after return statement
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 5 support in Mozilla
  • ECMAScript 6 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

JavaScript Debugging Toolkit: Identifying and Fixing "Invalid assignment left-hand side"

This error arises when you attempt to assign a value to something that cannot be assigned to. JavaScript requires valid "left-hand sides" (targets) for assignments, which are typically variables, object properties, or array elements.

Correct Usage:

  • Declared variables ( var , let , or const )
  • Existing variables
  • Object properties directly (without functions)
  • Array elements using their numerical indices ( myArray[0] = 5 )

Incorrect Usage:

  • Attempting to assign to expressions or values returned by functions
  • Assigning to undeclared variables (causes ReferenceError )
  • Using incorrect keywords or operators (e.g., using = for comparison instead of == or === )

Sample Code:

Precautions:

  • Carefully check variable declaration (using var , let , or const ) to avoid undeclared variable errors.
  • Remember that constants ( const ) cannot be reassigned after declaration.
  • Use == or === for comparisons, not = for assignments.
  • Be mindful of operator precedence (assignment has lower precedence than logical operators like && ).
  • For object properties and array elements, ensure the object or array exists before assignment.
  • ReferenceError: Occurs when trying to assign to an undeclared variable.
  • TypeError: Occurs when trying to assign to a value that cannot be hold a value (e.g., modifying a constant or a returned function value).
  • SyntaxError: Occurs if the code has incorrect syntax issues that prevent parsing.

Key Points:

  • Understand the different assignment operators and when to use them.
  • Declare variables before using them (except var , which has hoisting).
  • Be mindful of object property and array element accessibility.
  • Use strict equality comparison ( === ) or loose equality ( == ) instead of single assignment ( = ) for comparisons.
  • Practice debugging techniques to identify and fix assignment errors.
  • Consider using linters or code analysis tools to catch potential errors early.

By following these guidelines and carefully avoiding incorrect assignment scenarios, you can write clearer, more robust JavaScript code.

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 or ReferenceError , depending on the syntax.

What went wrong?

There was an unexpected assignment somewhere. This might be due to a mismatch of an assignment operator and an equality operator , for example. While a single = sign assigns a value to a variable, the == or === operators compare a value.

Typical invalid assignments

In the if statement, you want to use an equality operator ( === ), and for the string concatenation, the plus ( + ) operator is needed.

Assignments producing ReferenceErrors

Invalid assignments don't always produce syntax errors. Sometimes the syntax is almost correct, but at runtime, the left hand side expression evaluates to a value instead of a reference , so the assignment is still invalid. Such errors occur later in execution, when the statement is actually executed.

Function calls, new calls, super() , and this are all values instead of references. If you want to use them on the left hand side, the assignment target needs to be a property of their produced values instead.

Note: In Firefox and Safari, the first example produces a ReferenceError in non-strict mode, and a SyntaxError in strict mode . Chrome throws a runtime ReferenceError for both strict and non-strict modes.

Using optional chaining as assignment target

Optional chaining is not a valid target of assignment.

Instead, you have to first guard the nullish case.

  • Assignment operators
  • Equality operators

© 2005–2023 MDN contributors. Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side

Taming Asynchronous Beasts: Error Handling in JavaScript's Async/Await

Here's a breakdown of the terms you mentioned:JavaScript:A popular scripting language used for web development and other applications

  • JavaScript: Master Function Basics and Avoid the "Missing Curly After Function Body" Error
  • Combining JavaScript and Regular Expressions: Powerful Techniques for String Manipulation
  • Stepping into Strict Mode: JavaScript's Evolution and the Deprecation of caller and arguments

invalid left hand side in assignment

Working with UTC Time in JavaScript: Essential Considerations

invalid left hand side in assignment

Demystifying JavaScript's Date.getUTCDate(): Your Guide to UTC Day Extraction

Javascript's array.fromasync: a peek into the future of asynchronous arrays.

invalid left hand side in assignment

IMAGES

  1. Salesforce: Invalid left-hand side in assignment?

    invalid left hand side in assignment

  2. Invalid Left Hand Side in Assignment: Discover the Fix

    invalid left hand side in assignment

  3. R Error : invalid (do_set) left-hand side to assignment (2 Examples)

    invalid left hand side in assignment

  4. javascript

    invalid left hand side in assignment

  5. javascript

    invalid left hand side in assignment

  6. Invalid Left Hand Side in Assignment: Discover the Fix

    invalid left hand side in assignment

VIDEO

  1. FNF Invalid Data S-side charts

  2. LEFT HAND SIDE VIEW OF MY

  3. FNF Invalid Data S-side charts WEEK 5 full playthrough

  4. I hand out invalid lotto "winners" to panhandlers... #shorts

  5. invalid data s side chart cancelled builds

  6. He Left His own assignment