The left-hand side of assignment expression may not be an optional property access

avatar

Last updated: Feb 28, 2024 Reading time · 4 min

banner

# The left-hand side of assignment expression may not be an optional property access

The error "The left-hand side of an assignment expression may not be an optional property access" occurs when we try to use optional chaining (?.) to assign a property to an object.

To solve the error, use an if statement that serves as a type guard instead.

Here is an example of how the error occurs.

left hand side of assignment expression may not be optional property

We aren't allowed to use the optional chaining (?.) operator on the left-hand side of an assignment.

# Use an if statement as a type guard to solve the error

To solve the error, use an if statement as a type guard before the assignment.

use if statement as type guard to solve the error

We used the loose not equals operator (!=), to check if the variable is NOT equal to null and undefined .

This works because when compared loosely, null is equal to undefined .

The if block is only run if employee doesn't store an undefined or a null value.

This is similar to what the optional chaining (?.) operator does.

# Using the non-null assertion operator to solve the error

You might also see examples online that use the non-null assertion operator to solve the error.

The exclamation mark is the non-null assertion operator in TypeScript.

When you use this approach, you basically tell TypeScript that this value will never be null or undefined .

Here is an example of using this approach to set a property on an object.

using non null assertion to solve the error

In most cases, you should use a simple if statement that serves as a type guard as we did in the previous code sample.

# Avoiding the error with a type assertion

You can also use a type assertion to avoid getting the error. However, this isn't recommended.

avoiding the error with type assertion

The (employee as Employee) syntax is called a type assertion.

Type assertions are used when we have information about the type of a value that TypeScript can't know about.

We effectively tell TypeScript that the employee variable will have a type of Employee and not to worry about it.

This could go wrong if the variable is null or undefined as accessing a property on a null or an undefined value would cause a runtime error.

# Using the logical AND (&&) operator to get around the error

You can also use the logical AND (&&) operator to avoid getting the error.

using logical and operator to get around the error

The logical AND (&&) operator checks if the value to the left is truthy before evaluating the statement in the parentheses.

If the employee variable stores a falsy value (e.g. null or undefined ), the code to the right of the logical AND (&&) operator won't run at all.

The falsy values in JavaScript are: false , undefined , null , 0 , "" (empty string), NaN (not a number).

All other values are truthy.

However, this approach can only be used to assign a single property at a time if the value is not equal to null and undefined .

# The optional chaining operator should only be used when accessing properties

The optional chaining (?.) operator short-circuits if the reference is equal to null or undefined .

The optional chaining (?.) operator will simply return undefined in the example because employee has a value of undefined .

The purpose of the optional chaining (?.) operator is accessing deeply nested properties without erroring out if a value in the chain is equal to null or undefined .

However, the optional chaining operator cannot be used on the left-hand side of an assignment expression.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • How to Check the Type of a Variable in TypeScript
  • Exclamation Mark (non-null assertion) operator in TypeScript
  • The ?. operator (optional chaining) in TypeScript
  • Declare and Type a nested Object in TypeScript
  • How to Add a property to an Object in TypeScript
  • Check if a Property exists in an Object in TypeScript
  • The left-hand side of an arithmetic operation must be type 'any', 'number', 'bigint' or an enum type

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

How to fix SyntaxError: invalid assignment left-hand side

invalid left hand side in assignment expression jest

Let me show you an example that causes this error and how I fix it.

How to reproduce this error

How to fix this error, other causes for this error.

You can also see this error when you use optional chaining as the assignment target.

Take your skills to the next level ⚡️

Airbrake logo144-1

  • Get Started

Jan 26, 2017 6:00:03 AM | JavaScript - ReferenceError: invalid assignment left-hand side

Today we examine the invalid assignment error, which is thrown, as the name implies, when code attempts to perform an invalid assignment somewhere.

Next on the list in our extensive JavaScript Error Handling series we're going to examine the Invalid Left-Hand Assignment error in greater detail. The Invalid Left-Hand Assignment error is a sub-object of ReferenceError and is thrown, as the name implies, when code attempts to perform an invalid assignment somewhere.

In this post we'll look at a few code examples to illustrate some common methods of producing an Invalid Left-Hand Assignment error, as well as examine how to handle this error when it rears its ugly head. Let the party begin!

The Technical Rundown

  • All JavaScript error objects are descendants of the  Error  object, or an inherited object therein.
  • The  ReferenceError  object is inherited from the  Error  object.
  • The Invalid Left-Hand Assignment error is a specific type of ReferenceError object.

When Should You Use It?

As one of the simplest JavaScript errors to understand, the Invalid Left-Hand Assignment error appears in only a handful of situations in which code is attempting to pass an assignment incorrectly. While this is generally thought of as a syntactic issue, JavaScript defines this particular assignment error as a ReferenceError, since the engine effectively assumes an assignment to a non-referenced variable is being attempted.

The most common example of an Invalid Left-Hand Assignment error is when attempting to compare a value using a assignment operator (=), rather than using a proper comparison operator (== or ===). For example, here we're attempting to perform a basic comparison of the variable name with the values John or Fred. Unfortunately, we've made the mistake of using the assignment operator =, instead of a comparison operator such as == or ===:

try { var name = 'Bob'; if (name = 'John' || name = 'Fred') { console.log(`${name} returns!`) } else { console.log(`Just ${name} this time.`) } } catch (e) { if (e instanceof ReferenceError) { printError(e, true); } else { printError(e, false); } }

Sure enough, rather than giving us an output, the JavaScript engine produces the expected Invalid Left-Hand Assignment error:

It's worth noting that catching an Invalid Left-Hand Assignment error with a typical try-catch block is particular difficult, because the engine parses the code from inside out, meaning inner code blocks are parsed and executed before outer blocks. Since the issue of using a = assignment operator instead of a == comparison operator means the actual structure of the code is changed from the expected, the outer try-catch fails to be parsed and properly executed. In short, this means Invalid Left-Hand Assignment errors are always "raw", without any simple means of catching them.

Another common method for producing an Invalid Left-Hand Assignment error is when attempting to concatenate a string value onto a variable using the addition assignment += operator, instead of the concatenation operator +. For example, below we're attempting to perform concatenation on the name variable on multiple lines, but we've accidentally used the += operator:

try { var name = 'Bob' += ' Smith';

console.log(`Name is ${name}.`); } catch (e) { if (e instanceof ReferenceError) { printError(e, true); } else { printError(e, false); } }

This isn't the syntax JavaScript expects when concatenating multiple values onto a string, so an Invalid Left-Hand Assignment error is thrown:

To resolve this, we simply need to replace += with the concatenation operator +:

try { var name = 'Bob' + ' Smith';

Now we skip the Invalid Left-Hand Assignment error entirely and get our expected output indicating the full name stored in the name variable:

To dive even deeper into understanding how your applications deal with JavaScript Errors, check out the revolutionary Airbrake JavaScript error tracking tool for real-time alerts and instantaneous insight into what went wrong with your JavaScript code.

Written By: Frances Banks

You may also like.

 alt=

Dec 28, 2016 8:00:56 AM | JavaScript Error Handling - ReferenceError: assignment to undeclared variable “x”

Feb 15, 2017 7:41:35 am | javascript error handling: syntaxerror: "use strict" not allowed in function with non-simple parameters, may 21, 2017 9:00:51 am | javascript errors - syntaxerror: test for equality mistyped as assignment.

© Airbrake. All rights reserved. Terms of Service | Privacy Policy | DPA

  • 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

ReferenceError: invalid assignment left-hand side

The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. For example, a single " = " sign was used instead of " == " or " === ".

ReferenceError .

What went wrong?

There was an unexpected assignment somewhere. This might be due to a mismatch of a 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.

  • Assignment operators
  • Equality operators

© 2005–2021 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

  • Skip to main content

UDN Web Docs: MDN Backup

  • ReferenceError: invalid assignment left-hand side

The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. For example, a single " = " sign was used instead of " == " or " === ".

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.

Typical invalid assignments

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
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • 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
  • Using promises
  • Iterators and generators
  • Meta programming
  • JavaScript modules
  • Client-side web APIs
  • 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:
  • AggregateError
  • ArrayBuffer
  • AsyncFunction
  • BigInt64Array
  • BigUint64Array
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • ReferenceError
  • SharedArrayBuffer
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Bitwise operators
  • Comma operator
  • Conditional (ternary) operator
  • Destructuring assignment
  • Function expression
  • Grouping operator
  • Logical operators
  • Nullish coalescing operator
  • Object initializer
  • Operator precedence
  • Optional chaining
  • Pipeline operator
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function* expression
  • in operator
  • new operator
  • void operator
  • async function
  • for await...of
  • function declaration
  • import.meta
  • try...catch
  • Arrow function expressions
  • Default parameters
  • Method definitions
  • Rest parameters
  • The arguments object
  • Class fields
  • 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: invalid date
  • 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: can't access lexical declaration "x" before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the "delete" operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • 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 not a non-null object
  • TypeError: "x" is read-only
  • TypeError: "x" is not iterable
  • TypeError: More arguments needed
  • TypeError: Reduce of empty array with no initial value
  • TypeError: X.prototype.y called on incompatible type
  • TypeError: can't access dead object
  • TypeError: can't access property "x" of "y"
  • TypeError: can't assign to property "x" on "y": not an object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cannot use "in" operator to search for "x" in "y"
  • TypeError: cyclic object value
  • TypeError: invalid "instanceof" operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • DSA with JS - Self Paced
  • 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 Error Object Complete Reference

JS Range Error

  • JavaScript RangeError - Invalid date
  • JavaScript RangeError - Repeat count must be non-negative

JS Reference Error

  • JavaScript ReferenceError - Can't access lexical declaration`variable' before initialization
  • JavaScript ReferenceError - Invalid assignment left-hand side
  • JavaScript ReferenceError - Assignment to undeclared variable
  • JavaScript ReferenceError - Reference to undefined property "x"
  • JavaScript ReferenceError - variable is not defined
  • JavaScript ReferenceError Deprecated caller or arguments usage

JS Syntax Error

  • JavaScript SyntaxError - Illegal character
  • JavaScript SyntaxError - Identifier starts immediately after numeric literal
  • JavaScript SyntaxError - Function statement requires a name
  • JavaScript SyntaxError - Missing } after function body
  • JavaScript SyntaxError - Missing } after property list
  • JavaScript SyntaxError - Missing variable name
  • JavaScript SyntaxError - Missing ] after element list
  • JavaScript SyntaxError - Invalid regular expression flag "x"
  • JavaScript SyntaxError "variable" is a reserved identifier
  • JavaScript SyntaxError - Missing ':' after property id
  • JavaScript SyntaxError - Missing ) after condition
  • JavaScript SyntaxError - Missing formal parameter
  • JavaScript SyntaxError - Missing ; before statement
  • JavaScript SyntaxError - Missing = in const declaration
  • JavaScript SyntaxError - Missing name after . operator
  • JavaScript SyntaxError - Redeclaration of formal parameter "x"
  • JavaScript SyntaxError - Missing ) after argument list
  • JavaScript SyntaxError - Return not in function
  • JavaScript SyntaxError: Unterminated string literal
  • JavaScript SyntaxError - Applying the 'delete' operator to an unqualified name is deprecated
  • JavaScript SyntaxError - Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • JavaScript SyntaxError - Malformed formal parameter
  • JavaScript SyntaxError - "0"-prefixed octal literals and octal escape sequences are deprecated
  • JavaScript SyntaxError - Test for equality (==) mistyped as assignment (=)?
  • JavaScript SyntaxError - "x" is not a legal ECMA-262 octal constant

JS Type Error

  • JavaScript TypeError - "X" is not a non-null object
  • JavaScript TypeError - "X" is not a constructor
  • JavaScript TypeError - "X" has no properties
  • JavaScript TypeError - "X" is (not) "Y"
  • JavaScript TypeError - "X" is not a function
  • JavaScript TypeError - 'X' is not iterable
  • JavaScript TypeError - More arguments needed
  • JavaScript TypeError - "X" is read-only
  • JavaScript TypeError - Reduce of empty array with no initial value
  • JavaScript TypeError - Can't assign to property "X" on "Y": not an object
  • JavaScript TypeError - Can't access property "X" of "Y"
  • JavaScript TypeError - Can't define property "X": "Obj" is not extensible
  • JavaScript TypeError - X.prototype.y called on incompatible type
  • JavaScript TypeError - Invalid assignment to const "X"
  • JavaScript TypeError - Property "X" is non-configurable and can't be deleted
  • JavaScript TypeError - Can't redefine non-configurable property "x"
  • JavaScript TypeError - Variable "x" redeclares argument
  • JavaScript TypeError - Setting getter-only property "x"
  • JavaScript TypeError - Invalid 'instanceof' operand 'x'
  • JavaScript TypeError - Invalid Array.prototype.sort argument
  • JavaScript TypeError - Cyclic object value
  • JavaScript TypeError - Can't delete non-configurable array element

JS Other Errors

  • JavaScript URIError | Malformed URI Sequence
  • JavaScript Warning - Date.prototype.toLocaleFormat is deprecated
  • Logging Script Errors in JavaScript

JS Error Instance

  • JavaScript Error message Property
  • JavaScript Error name Property
  • JavaScript Error.prototype.toString() Method

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: 

Please Login to comment...

Similar reads.

  • JavaScript-Errors
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Invalid left-hand side in assignment expression

Hello. I am attempting to create a self-generating biology question that randomly generates three numbers for the problem question, then asks a yes or no question. When I was attempting to create the function that checks for the answer to the question and compared it to the student input, I get the “Invalid left-hand side in assignment expression”

My code is here, line 33 in the JavaScript window: https://codepen.io/KDalang/pen/OJpEdQB

Here is the specific line in question: if (chiTotal <= 3.841 && input=“Yes”) What did I do wrong?

= is assignment of a value to a variable == is weak comparison (with type coercion) === is strong comparison (probably what you want)

Hey thanks for the quick reply! I actually want it to be a “less than or equal to” and I used <=. <== and <=== don’t do anything either.

Edit: Nevermind, I understand now.

Do you try to compare values or do you try to assign a value?

Oh my gosh! Sorry its 2a.m. over here I understand what you and JeremyLT are saying now. Thanks so much!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript: Invalid left-hand side in assignment expression (2:0) #7638

@lukescott

lukescott commented Mar 27, 2018 • edited

Bug

num: number | undefined num! += 1

No Errors

I discovered this while pulling in a piece of code we were compiling with tsc. If you copy this code into the TypeScript playground it works fine.

My work-around for now was to change it to:

num: number | undefined num = num! + 1
software version(s)
Babel 7.0.0 beta 42
node 8.5.0
npm 5.3.0
Operating System OS X 10.12.2

The text was updated successfully, but these errors were encountered:

@babel-bot

babel-bot commented Mar 27, 2018

Hey ! We really appreciate you taking the time to report an issue. The collaborators
on this project attempt to help as many people as possible, but we're a limited number of volunteers,
so it's possible this won't be addressed swiftly.

If you need any help, or just have general Babel or JavaScript questions, we have a vibrant Slack
community that typically always has someone willing to help. You can sign-up
for an invite.

Sorry, something went wrong.

@hzoo

Successfully merging a pull request may close this issue.

@existentialism

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

ReferenceError: Invalid left-hand side in assignment

my code for a rock paper scissors game (called toss) is as follows:

When I enter in the parameters

I get this error code:

"ReferenceError: Invalid left-hand side in assignment"

How to fix it? What this error means and what other cases when this error can happen?

Alexei Levenkov's user avatar

  • 2 The three "tie" cases can be simplified into a single if( one == two) –  Niet the Dark Absol Sep 3, 2013 at 17:01

3 Answers 3

You have to use == to compare (or even === , if you want to compare types). A single = is for assignment.

Joseph Silber's user avatar

  • 2 for clarification, what would the difference be between == and ===? –  Kevin Sep 3, 2013 at 17:23
  • The above comment is sort of wrong, ECMA specifies that this is not a type check, it does an operation called type coercion. This is really useful to know, see this answer stackoverflow.com/questions/19915688/… –  VladNeacsu Sep 7, 2015 at 6:45
  • @Kevin stackoverflow.com/questions/359494/… –  Grant Aug 3, 2018 at 17:46

Common reasons for the error:

  • use of assignment ( = ) instead of equality ( == / === )
  • assigning to result of function foo() = 42 instead of passing arguments ( foo(42) )
  • simply missing member names (i.e. assuming some default selection) : getFoo() = 42 instead of getFoo().theAnswer = 42 or array indexing getArray() = 42 instead of getArray()[0]= 42

In this particular case you want to use == (or better === - What exactly is Type Coercion in Javascript? ) to check for equality (like if(one === "rock" && two === "rock") , but it the actual reason you are getting the error is trickier.

The reason for the error is Operator precedence . In particular we are looking for && (precedence 6) and = (precedence 3).

Let's put braces in the expression according to priority - && is higher than = so it is executed first similar how one would do 3+4*5+6 as 3+(4*5)+6 :

Now we have expression similar to multiple assignments like a = b = 42 which due to right-to-left associativity executed as a = (b = 42) . So adding more braces:

Finally we arrived to actual problem: ("rock" && two) can't be evaluated to l-value that can be assigned to (in this particular case it will be value of two as truthy ).

Note that if you'd use braces to match perceived priority surrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do && on two strings "rock" && "rock" resulting in "rock" (which in turn is truthy) all the time due to behavior of logial && :

For even more details on the error and other cases when it can happen - see specification:

LeftHandSideExpression = AssignmentExpression ... Throw a SyntaxError exception if the following conditions are all true: ... IsStrictReference(lref) is true

Left-Hand-Side Expressions

and The Reference Specification Type explaining IsStrictReference:

... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...

Community's user avatar

  • Good tip. Also, to add some information, I had this error in my code once, and coudn´t find out why, because it was kind of simple. I was using inline javascript, for example: <a onmouseover="imgIte123-a.src='layout-bto-gol.png';"> and it was returning me this error. The problem was with the dash in the id. I had to change the id to imgIte123_a and everything worked fine. –  Jorge Mauricio Feb 8, 2020 at 17:24

The same happened for me with eslint module. EsLinter throw Parsing error: Invalid left-hand side in assignment expression for await in second if statement.

As strange as it sounds what fixed this error was to add ; semicolon at the end of line where await occurred.

Lukasz Dynowski's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript logic or ask your own question .

  • Featured on Meta
  • The 2024 Developer Survey Is Live
  • The return of Staging Ground to Stack Overflow
  • The [tax] tag is being burninated
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • NES Emulator in C
  • What legal reason, if any, does my bank have to know if I am a dual citizen of the US?
  • Moving after copying in assignment of conditional operator result
  • How might a physicist define 'mind' using concepts of physics?
  • Unicode character └ (U+2514) not set up with LaTeX (when using) pandoc with markdown text file
  • Calculation of centrifugal liquid propellant injectors
  • I'm looking for a series where there was a civilization in the Mediterranean basin, which got destroyed by the Atlantic breaking in
  • Does it make sense for giants to use clubs or swords when fighting non-giants?
  • An application of the (100/e)% rule applied to postdocs: moving on from an academic career, perhaps
  • Application of Lie group analysis of PDE (beyond calculation of exact solutions)
  • Why do we say "he doesn't know him from Adam"?
  • Build the first 6 letters of an Italian codice fiscale (tax identification number)
  • Is the barrier to entry for mathematics research increasing, and is it at risk of becoming less accessible in the future?
  • How to use ogr2ogr -segmentize on a CSV file?
  • How do I tell which kit lens option is more all-purpose?
  • XeLaTeX+polyglossia+french+biblatex complain about missing character (U+200B)
  • What is the U.N. list of shame and how does it affect Israel which was recently added?
  • Converting NEMA 10-30 to 14-30 using ground from adjacent 15 amp receptacle
  • Handling cases of "potential" ChatGPT-generated reviews in non-anonymous program committees (as a PC member)
  • Power series representation of 1/(2+x)
  • A phrase that means you are indifferent towards the things you are familiar with?
  • Print all correct parenthesis sequences of () and [] of length n in lexicographical order
  • Can LLMs have intention?
  • How can/do I find the "main root" for wild grape vine in my yard?

invalid left hand side in assignment expression jest

COMMENTS

  1. SyntaxError: invalid assignment left-hand side

    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. js. function foo() { return { a: 1 }; } foo ...

  2. Why I get "Invalid left-hand side in assignment"?

    7. The problem is that the assignment operator, =, is a low-precedence operator, so it's being interpreted in a way you don't expect. If you put that last expression in parentheses, it works: for(let id in list)(. (!q.id || (id == q.id)) &&. (!q.name || (list[id].name.search(q.name) > -1)) &&. (result[id] = list[id]) ); The real problem is ...

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

    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.

  4. The left-hand side of assignment expression may not be an optional

    The optional chaining (?.) operator will simply return undefined in the example because employee has a value of undefined.. The purpose of the optional chaining (?.) operator is accessing deeply nested properties without erroring out if a value in the chain is equal to null or undefined. However, the optional chaining operator cannot be used on the left-hand side of an assignment expression.

  5. How to fix SyntaxError: invalid assignment left-hand side

    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.

  6. JavaScript

    Today we examine the invalid assignment error, which is thrown, as the name implies, when code attempts to perform an invalid assignment somewhere.

  7. ReferenceError: invalid assignment left-hand side

    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.

  8. Errors: Invalid assignment left-hand side

    ReferenceError: invalid assignment left-hand side The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. For example, a single "=" sign was used instead of "==" or "===". ... Errors: Deprecated expression closures. Errors: Deprecated octal. Errors: Deprecated source map pragma ...

  9. ReferenceError: invalid assignment left-hand side

    The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere. For example, a single "=" sign was used instead of "==" or "===". ... SyntaxError: invalid regular expression flag "x" SyntaxError: missing ) after argument list; SyntaxError: missing ) after condition;

  10. Optional chaining (?.)

    const object = {}; object?. property = 1; // SyntaxError: Invalid left-hand side in assignment Short-circuiting When using optional chaining with expressions, if the left operand is null or undefined , the expression will not be evaluated.

  11. Invalid assignment left-hand side

    The Left Shift Assignment Operator is represented by "<<=". This operator moves the specified number of bits to the left and assigns that result to the variable. We can fill the vacated place by 0. The left shift operator treats the integer stored in the variable to the operator's left as a 32-bit binary number. This can also be explained as

  12. Invalid left-hand side in assignment expression

    Hello. I am attempting to create a self-generating biology question that randomly generates three numbers for the problem question, then asks a yes or no question. When I was attempting to create the function that checks for the answer to the question and compared it to the student input, I get the "Invalid left-hand side in assignment expression" My code is here, line 33 in the JavaScript ...

  13. Typescript : Invalid left-hand side of assignment expression

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

  14. [Error] Invalid left-hand side expression in prefix operation #242

    Does anyone have any ideas of why I continue to get the Invalid left-hand side expression in prefix operation error? Any advice would be much appreciated. The text was updated successfully, but these errors were encountered: All reactions. Copy link Owner. shama ...

  15. TypeScript: Invalid left-hand side in assignment expression (2:0)

    TypeScript: Invalid left-hand side in assignment expression (2:0) #7638. Closed lukescott opened this issue Mar 27, 2018 · 1 comment · Fixed by #7888. ... Invalid left-hand side in assignment expression (2:0) Context. I discovered this while pulling in a piece of code we were compiling with tsc. If you copy this code into the TypeScript ...

  16. ReferenceError: invalid assignment left-hand side

    ReferenceError: invalid assignment left-hand side. JavaScript の例外 "invalid assignment left-hand side" は、どこかで予想外の代入が行われたときに発生します。. 例えば、単一の " = " の記号が " == " や " === " の代わりに使用された場合です。.

  17. javascript

    0. You're first approach is about retrieval data. Whereas the second part is about assigning the data. Here You're are assigning value to something function variable. May you need to change like below. function something(id, val){. document.getElementById(id).value = val; return document.getElementById(id).value; }

  18. ReferenceError: Invalid left-hand side in assignment

    Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.

  19. ReferenceError: invalid assignment left-hand side

    SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**' SyntaxError: unterminated string literal; SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead ... // ReferenceError: invalid assignment left-hand side var str = 'Hello, ...