How to fix SyntaxError: invalid assignment left-hand side
Let me show you an example that causes this error and how I fix it.
![](http://ortec.site/777/templates/cheerup1/res/banner1.gif)
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 ⚡️
Invalid left-hand side in assignment in JavaScript [Solved]
![t syntaxerror invalid left hand side in assignment avatar](https://bobbyhadz.com/images/global/avatar.webp)
Last updated: Mar 2, 2024 Reading time · 2 min
![t syntaxerror invalid left hand side in assignment banner](https://bobbyhadz.com/images/blog/javascript-invalid-left-hand-side-in-assignment/banner.webp)
# 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.
![t syntaxerror invalid left hand side in assignment invalid left hand side in assignment error](https://bobbyhadz.com/images/blog/javascript-invalid-left-hand-side-in-assignment/invalid-left-hand-side-in-assignment-error.webp)
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.
![t syntaxerror invalid left hand side in assignment use double or triple equals when comparing values](https://bobbyhadz.com/images/blog/javascript-invalid-left-hand-side-in-assignment/use-double-or-triple-equals-when-comparing-values.webp)
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.
![t syntaxerror invalid left hand side in assignment assignment vs equality](https://bobbyhadz.com/images/blog/javascript-invalid-left-hand-side-in-assignment/assignment-vs-equality.webp)
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.
![t syntaxerror invalid left hand side in assignment use bracket notation for object properties containing hyphens](https://bobbyhadz.com/images/blog/javascript-invalid-left-hand-side-in-assignment/use-bracket-notation-for-object-properties-containing-hyphens.webp)
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.
![t syntaxerror invalid left hand side in assignment book cover](https://bobbyhadz.com/images/global/book-cover.webp)
Borislav Hadzhiev
Web Developer
![t syntaxerror invalid left hand side in assignment buy me a coffee](https://bobbyhadz.com/images/global/sidebar-book-small.webp)
Copyright © 2024 Borislav Hadzhiev
Fixing Assignment Errors in JavaScript: 'Invalid left-hand side'
- "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:
Mistaking Comparison for Assignment:
- 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.
- Constants declared with const .
Incorrect Object Property Access:
Fixing the Error:
Double-Check Comparisons:
Verify Object 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.
- 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.
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.
Additional Cautions:
- 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.
- 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.
Related Example Codes for "Invalid assignment left-hand side" Errors in JavaScript:
A. document.getElementById Result:
B. const Variables:
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.
Here's a different way to think about it:
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.
Error Message:"Errors: Invalid date" is a common error you might encounter in JavaScript code when you try to work with dates but provide invalid data
Understanding the Error:This error occurs when you use the instanceof operator incorrectly in your JavaScript code. The instanceof operator is used to check whether an object was created by a specific constructor function
Error Message:"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
Understanding the Error:JavaScript: JavaScript is a programming language commonly used to create interactive web pages and applications
Understanding the Error:What it is: This error indicates that JavaScript encountered a malformed (incorrectly formatted) Uniform Resource Identifier (URI) while trying to process a web address or URL
Error Message:"Errors: Missing initializer in const"What it Means:This 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
Error Message:"Missing parenthesis after argument list"Meaning:This error arises in JavaScript when you call a function or method but forget to include the closing parenthesis ')' after the list of arguments you're passing to it
SyntaxError: invalid assignment left-hand side
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
![Airbrake logo144-1 Airbrake logo144-1](https://blog.airbrake.io/hs-fs/hubfs/Airbrake%20logo144-1.png?width=158&height=28&name=Airbrake%20logo144-1.png)
- 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.
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, dec 9, 2016 5:00:00 am | javascript error handling - rangeerror: argument is not a valid code point.
© Airbrake. All rights reserved. Terms of Service | Privacy Policy | DPA
![t syntaxerror invalid left hand side in assignment The Linux Code](https://thelinuxcode.com/wp-content/uploads/2023/10/The-Linux-Code-83x83.webp)
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.
![](http://ortec.site/777/templates/cheerup1/res/banner1.gif)
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…
A Beginner‘s Guide to Formatting Decimal Places in JavaScript
As a web developer, you‘ll frequently run into situations where you need to display nice, cleanly formatted numbers in your interfaces. Have you ever had…
A Complete Guide to Dynamic DOM Manipulation with JavaScript‘s appendChild()
As a Linux developer building modern web applications, being able to efficiently interact with the DOM (Document Object Model) using JavaScript is a crucial skill.…
A Complete Guide to Dynamically Adding Properties in JavaScript
As an experienced JavaScript developer, I often get asked about the different ways to add properties to objects in JavaScript. While this may seem like…
A Complete Guide to Dynamically Changing Image Sources with JavaScript
This comprehensive tutorial explains how to change image sources dynamically in JavaScript. We‘ll cover the ins and outs of swapping images on the fly using…
- 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 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.
- Web Technologies
- JavaScript-Errors
- Top Android Apps for 2024
- Top Cell Phone Signal Boosters in 2024
- Best Travel Apps (Paid & Free) in 2024
- The Best Smart Home Devices for 2024
- 15 Most Important Aptitude Topics For Placements [2024]
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
- Skip to main content
![t syntaxerror invalid left hand side in assignment UDN Web Docs: MDN Backup](https://udn.realityripple.com/static/img/web-docs-black.png)
- 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
- 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
What went wrong?
ReferenceError .
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
- 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
- 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:
- ArrayBuffer
- AsyncFunction
- Float32Array
- Float64Array
- GeneratorFunction
- InternalError
- Intl.Collator
- Intl.DateTimeFormat
- Intl.ListFormat
- Intl.NumberFormat
- Intl.PluralRules
- Intl.RelativeTimeFormat
- SharedArrayBuffer
- SyntaxError
- Uint16Array
- Uint32Array
- Uint8ClampedArray
- WebAssembly
- 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
- (currently at stage 1) pipes the value of an expression into a function. This allows the creation of chained function calls in a readable manner. The result is syntactic sugar in which a function call with a single argument can be written like this:">Pipeline operator
- 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 await...of
- for each...in
- function declaration
- import.meta
- try...catch
- Arrow functions
- Default parameters
- Method definitions
- Rest parameters
- The arguments object
- constructor
- element loaded from a different domain for which you violated the same-origin policy.">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: can't access dead object
- TypeError: can't access property "x" of "y"
- 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
- X.prototype.y called on incompatible type
- JavaScript technologies overview
- Lexical grammar
- Enumerability and ownership of properties
- Iteration protocols
- Transitioning to strict mode
- Template literals
- Deprecated features
- ECMAScript 2015 support in Mozilla
- ECMAScript 5 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
Learn the best of web development
Get the latest and greatest from MDN delivered straight to your inbox.
Thanks! Please check your inbox to confirm your subscription.
If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us.
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.
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
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.
Google Script Invalid Assignment left-hand side
Ok so I have this code. Sorry, I didn't know where the problem is so I pasted it all. It says: Invalid assignment left-hand side. (line 1, file "Code"). I know the problem cannot be on line one but have no idea where it is.
- google-apps-script
- Line 1 is function send(sheet, email, row){ . Is that really where the error is? – Barmar Commented Aug 6, 2014 at 15:58
- That doesn't seem likely, since there's no assignment on that line. – Barmar Commented Aug 6, 2014 at 16:00
- Yeah, it says: Invalid assignment left-hand side. (line 1, file "Code") – rgavs Commented Aug 6, 2014 at 16:06
- And if you click on the error message, it takes you to the function line? – Barmar Commented Aug 6, 2014 at 16:12
- Yes it highlights the function send line – rgavs Commented Aug 6, 2014 at 16:14
You cannot write a line like this : ( 2 x += in the same statement)
I'd suggest to use an intermediate variable like this :
if this is really what you want to do... but it seems strange to me...
Shouldn't it be something like this : body+= '\n'+sheet.getRange(temp + 1,11);
- So I don't need to use an intermediate variable, edited line 15 from: body += '\n' + body += '\n' + sheet.getRange(temp + 1,11); to body += '\n' + body + '\n' + sheet.getRange(temp + 1,11); cutting out the repeated += operator within the same line. – rgavs Commented Aug 6, 2014 at 16:35
- indeed ... but why repeating body ? I must say I find it strange... Anyway, I don't know the use case ;-) thx for accepting . – Serge insas Commented Aug 6, 2014 at 16:37
- You know what, you're right, that was an accidental repetition – rgavs Commented Aug 6, 2014 at 17:37
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 google-apps-script or ask your own question .
- The Overflow Blog
- At scale, anything that could fail definitely will
- Featured on Meta
- Announcing a change to the data-dump process
- Bringing clarity to status tag usage on meta sites
- What does a new user need in a homepage experience on Stack Overflow?
- Feedback requested: How do you use tag hover descriptions for curating and do...
- Staging Ground Reviewer Motivation
Hot Network Questions
- How would humans actually colonize mars?
- Definition clarification on topology regarding closed set
- When trying to find the quartiles for discrete data, do we round to the nearest whole number?
- Velocity dispersion of stars in galaxies
- How should I secure ceiling drywall with no edge backing?
- Did Gandalf know he was a Maia?
- Marie-Sklodowska-Curie actions: publish a part of the proposal just after the deadline?
- quantulum abest, quo minus . .
- Can a British judge convict and sentence someone for contempt in their own court on the spot?
- How best to cut (slightly) varying size notches in long piece of trim
- Does an unseen creature with a burrow speed have advantage when attacking from underground?
- How to substitute URLs?
- Word for when someone tries to make others hate each other
- What difference does the USB-C connector make what orientation the cable connected to it is now?
- How can coordinates be meaningless in General Relativity?
- Strange variable scope behavior when calling function recursivly
- MANIFEST_UNKNOWN error: OCI index found, but Accept header does not support OCI indexes
- How do I safely download files of an older version software I want to dissect but don't want interferring with my already installed current version?
- How do Trinitarian Christians defend the unfalsifiability of the Trinity?
- What happens to entropy during compression?
- A novel (and a movie) about a village in southern France where a strange succession of events happens
- Is it a date format of YYMMDD, MMDDYY, and/or DDMMYY?
- Whats the safest way to store a password in database?
- Invest smaller lump sum vs investing (larger) monthly amount
![](http://ortec.site/777/templates/cheerup1/res/banner1.gif)
IMAGES
VIDEO
COMMENTS
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 ...
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 ...
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.
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.
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:
SyntaxError: 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 ===.
Today we examine the invalid assignment error, which is thrown, as the name implies, when code attempts to perform an invalid assignment somewhere.
Uncaught ReferenceError: Invalid left-hand side in assignment at myScript.js:2 Now that we've seen the error, let's walk through debugging techniques. Debugging an Invalid Assignment
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. A single "=" sign instead of "==" or "===" is an Invalid 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.
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 "===". Message ... SyntaxError: invalid regular expression flag "x" SyntaxError: missing ) after argument list; SyntaxError: missing ) after condition;
ReferenceError: invalid assignment left-hand side; 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
ReferenceError: invalid assignment left-hand side; 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
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 ...
JavaScript の例外 "invalid assignment left-hand side" は、どこかで予想外の代入が行われたときに発生します。 ... ReferenceError: invalid assignment left-hand side; SyntaxError: invalid BigInt syntax; SyntaxError: invalid capture group name in regular expression; SyntaxError: invalid character in class in regular ...
For some reason, I keep getting the following error: invalid assignment left-hand side at 9: line 10. My code is pretty simple and looks spot on AFAICT. Please review and tell me I'm not crazy. (Or tell me I am, but you have a solution :)) function jsNetworkAccount() {. // Get a reference to each check box. var f1 = getField("cbNetworkNotNeeded");
Because the employee is a class instead of an object, I think you have to call the constructor. So this should be what the employees would look like
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.