Invalid left-hand side in assignment in JavaScript [Solved]
![uncaught referenceerror invalid left hand side in assignment at object success avatar](https://bobbyhadz.com/images/global/avatar.webp)
Last updated: Mar 2, 2024 Reading time · 2 min
![uncaught referenceerror invalid left hand side in assignment at object success banner](https://bobbyhadz.com/images/blog/javascript-invalid-left-hand-side-in-assignment/banner.webp)
![](http://writinghelp.online/777/templates/cheerup/res/banner1.gif)
# 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.
![uncaught referenceerror invalid left hand side in assignment at object success 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.
![uncaught referenceerror invalid left hand side in assignment at object success 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.
![uncaught referenceerror invalid left hand side in assignment at object success 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.
![uncaught referenceerror invalid left hand side in assignment at object success 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.
![uncaught referenceerror invalid left hand side in assignment at object success book cover](https://bobbyhadz.com/images/global/book-cover.webp)
Borislav Hadzhiev
Web Developer
![uncaught referenceerror invalid left hand side in assignment at object success buy me a coffee](https://bobbyhadz.com/images/global/sidebar-book-small.webp)
Copyright © 2024 Borislav Hadzhiev
How to fix SyntaxError: invalid assignment left-hand side
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 ⚡️
Fixing Assignment Errors in JavaScript: 'Invalid left-hand side'
Errors: invalid assignment left-hand side.
Error Message:
- "Invalid assignment left-hand side"
What it Means:
This error arises in JavaScript when you attempt to assign a value to something that cannot be assigned to. In simpler terms, you're trying to put data (the value on the right side of the equal sign) into a location (the left side of the equal sign) that doesn't accept it.
Common Causes:
Here are some frequent scenarios that lead to this error:
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.
- The result of functions like document.getElementById() , which returns an element reference (you can modify the element's content using properties like innerHTML ).
- Constants declared with const .
Incorrect Object Property Access:
- If you attempt to assign to a non-existent property of an object, JavaScript might throw this error. Ensure the property exists before assignment.
Fixing the Error:
Double-Check Comparisons:
- Verify that you're using the correct operators ( == , === , != , etc.) for comparisons within conditional statements.
- If you need to modify a read-only value, consider alternative approaches. For example, create a new variable or use a property like innerHTML to change the content of an element.
Verify Object Properties:
- Before assigning to an object property, make sure the property exists. You can use the in operator or access it conditionally (e.g., if (obj.hasOwnProperty('property')) ).
Related Errors:
- 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:
Here's how you can approach the issue:
Understand the Error: The error signifies that you're trying to assign a value to something that can't be assigned to. This could be due to various reasons, as explained earlier.
Identify the Cause: Analyze your code to determine why the assignment is invalid. Refer to the related example codes to see if your situation matches any of them.
Fix the Issue: Depending on the cause, you might need to:
- Use comparison operators: If you're accidentally using an assignment operator ( = ) in a conditional statement, use the correct comparison operator (like == , === , != , etc.).
- Avoid read-only assignments: If you're trying to modify a read-only value (like document.getElementById result or a const variable), consider alternative approaches (e.g., modify element content using properties like innerHTML or declare a new variable).
- Ensure object properties exist: If you're assigning to a non-existent property of an object, check if the property exists before assigning.
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.
Resolving Malformed URI Errors for a Smooth JavaScript Experience
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
JavaScript Error Explained: 'invalid right hand side instanceof operand'
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
Troubleshooting JSON Parsing Errors: 'Errors: JSON bad parse' Explained
Understanding the Error:JavaScript: JavaScript is a programming language commonly used to create interactive web pages and applications
Troubleshooting String Errors in JavaScript: Beyond 'Unterminated String Literal'
Understanding the Error:In JavaScript, strings are used to represent text data. They are enclosed within quotation marks (either single quotes ' or double quotes ")
Understanding 'Not a Function' Errors in JavaScript: Causes and Solutions
Error Message:"Errors: Not a function" indicates that JavaScript encountered an attempt to call something as a function
![uncaught referenceerror invalid left hand side in assignment at object success uncaught referenceerror invalid left hand side in assignment at object success](https://runebook.dev/thumbnail/080.webp)
Understanding Constructors and Fixing 'Not a Constructor' Errors
Understanding and fixing 'errors: is not iterable' errors, understanding 'missing parenthesis after argument list' in javascript, fixing 'missing initializer in const': a guide for javascript developers.
![uncaught referenceerror invalid left hand side in assignment at object success uncaught referenceerror invalid left hand side in assignment at object success](https://runebook.dev/thumbnail/075.webp)
Creating Arrays in JavaScript: Avoiding 'Invalid Array Length'
Javascript dates: keeping your code safe from 'invalid date' errors, javascript error explained: missing semicolon before statement, say goodbye to deprecated features: alternatives for 'caller' and 'arguments' in javascript.
![uncaught referenceerror invalid left hand side in assignment at object success 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.
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…
![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, 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
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
- 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:
![](http://writinghelp.online/777/templates/cheerup/res/banner1.gif)
Please Login to comment...
Similar reads.
- Web Technologies
- JavaScript-Errors
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
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
© 2016 Mozilla 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
- Main Content
![uncaught referenceerror invalid left hand side in assignment at object success uncaught referenceerror invalid left hand side in assignment at object success](https://davidwalsh.name/wp-content/themes/punky/images/logo.png)
- JavaScript Promises
- ES6 Features
JavaScript Errors and How to Fix Them
JavaScript can be a nightmare to debug: Some errors it gives can be very difficult to understand at first, and the line numbers given aren’t always helpful either. Wouldn’t it be useful to have a list where you could look to find out what they mean and how to fix them? Here you go!
Below is a list of the strange errors in JavaScript. Different browsers can give you different messages for the same error, so there are several different examples where applicable.
How to read errors?
Before the list, let’s quickly look at the structure of an error message. Understanding the structure helps understand the errors, and you’ll have less trouble if you run into any errors not listed here.
A typical error from Chrome looks like this:
The structure of the error is as follows:
- Uncaught TypeError : This part of the message is usually not very useful. Uncaught means the error was not caught in a catch statement, and TypeError is the error’s name.
- undefined is not a function : This is the message part. With error messages, you have to read them very literally. For example in this case it literally means that the code attempted to use undefined like it was a function.
Other webkit-based browsers, like Safari, give errors in a similar format to Chrome. Errors from Firefox are similar, but do not always include the first part, and recent versions of Internet Explorer also give simpler errors than Chrome – but in this case, simpler does not always mean better.
Now onto the actual errors.
Uncaught TypeError: undefined is not a function
Related errors: number is not a function, object is not a function, string is not a function, Unhandled Error: ‘foo’ is not a function, Function Expected
Occurs when attempting to call a value like a function, where the value is not a function. For example:
This error typically occurs if you are trying to call a function in an object, but you typed the name wrong.
Since object properties that don’t exist are undefined by default, the above would result in this error.
The other variations such as “number is not a function” occur when attempting to call a number like it was a function.
How to fix this error: Ensure the function name is correct. With this error, the line number will usually point at the correct location.
Uncaught ReferenceError: Invalid left-hand side in assignment
Related errors: Uncaught exception: ReferenceError: Cannot assign to ‘functionCall()’, Uncaught exception: ReferenceError: Cannot assign to ‘this’
Caused by attempting to assign a value to something that cannot be assigned to.
The most common example of this error is with if-clauses:
In this example, the programmer accidentally used a single equals instead of two. The message “left-hand side in assignment” is referring to the part on the left side of the equals sign, so like you can see in the above example, the left-hand side contains something you can’t assign to, leading to the error.
How to fix this error: Make sure you’re not attempting to assign values to function results or to the this keyword.
Uncaught TypeError: Converting circular structure to JSON
Related errors: Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object, TypeError: cyclic object value, Circular reference in value argument not supported
Always caused by a circular reference in an object, which is then passed into JSON.stringify .
Because both a and b in the above example have a reference to each other, the resulting object cannot be converted into JSON.
How to fix this error: Remove circular references like in the example from any objects you want to convert into JSON.
Unexpected token ;
Related errors: Expected ), missing ) after argument list
The JavaScript interpreter expected something, but it wasn’t there. Typically caused by mismatched parentheses or brackets.
The token in this error can vary – it might say “Unexpected token ]” or “Expected {” etc.
How to fix this error: Sometimes the line number with this error doesn’t point to the correct place, making it difficult to fix.
- An error with [ ] { } ( ) is usually caused by a mismatching pair. Check that all your parentheses and brackets have a matching pair. In this case, line number will often point to something else than the problem character
- Unexpected / is related to regular expressions. The line number for this will usually be correct.
- Unexpected ; is usually caused by having a ; inside an object or array literal, or within the argument list of a function call. The line number will usually be correct for this case as well
Uncaught SyntaxError: Unexpected token ILLEGAL
Related errors: Unterminated String Literal, Invalid Line Terminator
A string literal is missing the closing quote.
How to fix this error: Ensure all strings have the correct closing quote.
Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined
Related errors: TypeError: someVal is null, Unable to get property ‘foo’ of undefined or null reference
Attempting to read null or undefined as if it was an object. For example:
How to fix this error: Usually caused by typos. Check that the variables used near the line number pointed by the error are correctly named.
Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined
Related errors: TypeError: someVal is undefined, Unable to set property ‘foo’ of undefined or null reference
Attempting to write null or undefined as if it was an object. For example:
How to fix this error: This too is usually caused by typos. Check the variable names near the line the error points to.
Uncaught RangeError: Maximum call stack size exceeded
Related errors: Uncaught exception: RangeError: Maximum recursion depth exceeded, too much recursion, Stack overflow
Usually caused by a bug in program logic, causing infinite recursive function calls.
How to fix this error: Check recursive functions for bugs that could cause them to keep recursing forever.
Uncaught URIError: URI malformed
Related errors: URIError: malformed URI sequence
Caused by an invalid decodeURIComponent call.
How to fix this error: Check that the decodeURIComponent call at the error’s line number gets correct input.
XMLHttpRequest cannot load http://some/url/. No ‘Access-Control-Allow-Origin’ header is present on the requested resource
Related errors: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://some/url/
This error is always caused by the usage of XMLHttpRequest.
How to fix this error: Ensure the request URL is correct and it respects the same-origin policy . A good way to find the offending code is to look at the URL in the error message and find it from your code.
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
Related errors: InvalidStateError, DOMException code 11
Means the code called a function that you should not call at the current state. Occurs usually with XMLHttpRequest , when attempting to call functions on it before it’s ready.
In this case, you would get the error because the setRequestHeader function can only be called after calling xhr.open .
How to fix this error: Look at the code on the line pointed by the error and make sure it runs at the correct time, or add any necessary calls before it (such as xhr.open )
JavaScript has some of the most unhelpful errors I’ve seen, with the exception of the notorious Expected T_PAAMAYIM_NEKUDOTAYIM in PHP. With more familiarity the errors start to make more sense. Modern browsers also help, as they no longer give the completely useless errors they used to.
What’s the most confusing error you’ve seen? Share the frustration in the comments!
![uncaught referenceerror invalid left hand side in assignment at object success Jani Hartikainen](https://davidwalsh.name/demo/JaniHartikainen.jpg)
Jani Hartikainen has spent over 10 years building web applications. His clients include companies like Nokia and hot super secret startups. When not programming or playing games, Jani writes about JavaScript and high quality code on his site.
codeutopia.net jhartikainen Posts
Recent Features
![uncaught referenceerror invalid left hand side in assignment at object success How I Stopped WordPress Comment Spam](https://davidwalsh.name/demo/JavaScriptListImage.png?preview)
How I Stopped WordPress Comment Spam
I love almost every part of being a tech blogger: learning, preaching, bantering, researching. The one part about blogging that I absolutely loathe: dealing with SPAM comments. For the past two years, my blog has registered 8,000+ SPAM comments per day. PER DAY. Bloating my database...
![uncaught referenceerror invalid left hand side in assignment at object success Vibration API](https://davidwalsh.name/demo/html5250.png?preview)
Vibration API
Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user. One of those simple APIs the Vibration API . The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...
Incredible Demos
![uncaught referenceerror invalid left hand side in assignment at object success iPad Detection Using JavaScript or PHP](https://davidwalsh.name/demo/ipads.png?preview)
iPad Detection Using JavaScript or PHP
The hottest device out there right now seems to be the iPad. iPad this, iPad that, iPod your mom. I'm underwhelmed with the device but that doesn't mean I shouldn't try to account for such devices on the websites I create. In Apple's...
![uncaught referenceerror invalid left hand side in assignment at object success WordPress-Style Comment Controls Using MooTools or jQuery](https://davidwalsh.name/demo/css3logo250.jpg?preview)
WordPress-Style Comment Controls Using MooTools or jQuery
WordPress has a nice little effect on the Admin Dashboard where it shows and hides the comment control links when you mouseover and mouseout of the record's container. Here's how to achieve that effect using MooTools or jQuery. The XHTML Notice that we place the links into...
To avoid RangeError errors- the best way might be changing recursions to loops, because browsers have limitations for JavaScript call stack- which is usually from 1525 (IE) to 334028 (FF). I prepared demo to check it in your browser:
http://codepen.io/malyw/pen/pvwoyK
Some Math calculation might take more cycles- so it’s good idea to change them to loops and move e.g. to Web Workers.
That’s a great tip Sergey. It’s true that in some algorithms, it’s possible to run into the recursion limitations without a bug.
This article nails JavaScript errors right on the head. Especially the one about the Unexpected[] or {}. I’ve had that point to the jQuery library when it was just within my own code!
Thanks for sharing!
You can eliminate a lot of these errors by using a linter like jshint or eslint. It’s useful to have a linter in your build process as well as in your editor.
Yeah, I’ve been looking at these kinds of tools lately. Others like Flow and TypeScript could also be useful, though may require a bit more work to set up.
Definitely a topic I might write about in the future!
“I’ve been looking at these kinds of tools lately”? Wow, I thought they were standard practice in the industry nowadays, does anyone really still run their code without checking it with some tool first?
For what is worth, eslint is vastly superior to jshint – more rules (and the ability to write your own), and it differentiates between errors and warnings (so you don’t have to stop a build because of unimportant formatting).
I had similar experience for Javascript, and decided the problem was with the actual language itself. I realise that there is not much point to use Javascript when there are languages available which are not limited and broken and are a pleasure to use and jebug.
Wow! good information very nice article I hope it helps me a lot thanks for sharing
Thanks for this very helpful article. Locating and rectifying error in a large Javascript code has been hugely frustrating, I some times prayed for the day, when some body develops a compiler, interpreter or any helpful tool to help us debug and remove errors.
Great article! Also, I agree with Till about using a linter like JSHint. It’s one way to save page reload time, typing to open the console, finding the correct line where the error occurred, deciphering some of the more cryptic error messages in certain browsers, and teaching good practices when the linter is configured correctly.
Very useful.Thanks!
Awesome article, well done. What further complicates the problem is that each browser has implemented {object Error} in a different way! The behavior and contents change wildly browser to browser. I did a talk on these differences last year:
http://vimeo.com/97537677
Running a JavaScript Error Logging service ( http://Trackjs.com ), we’ve seen tons of crazy errors. Sometimes devices or plugins overload behavior and use JavaScript as a transport layer. For example, Chrome on IOS overloads XmlHttpRequest with extra properties and uses it to communicate to the native webkit client. If you mess with the XmlHttpRequest on this platform, chrome shows tons of nasty security errors!
A code highlighting editor will pretty much make almost all of these errors except the circular JSON reference go away.
er.. and the other runtime errors that i didn’t notice at first glance. :-D
Be grateful you don’t still have to code for IE6, and it’s notoriously unhelpful “unspecified error at line 1” :-O
Thanks a bunch. Saved me a lot of stress
I’m getting an Uncaught TypeError when a response from a jsonp request is received after the timeout I specified. Most of the time it works. However, there are times that our api server is so heavily busy. How do I catch the error rather than seeing Uncaught TypeError in the console?
Thanks! Great site!
- oleg 9112334024676320 + 1 === 9112334024676320 //=> true //in node,chrome,firefox
Internet Explorer is generating the error “Unable to get property ‘chunkSize’ of undefined or null reference”. What does that mean?
I keep in running into “ORIGINAL EXCEPTION: TypeError: Cannot read property ‘request’ of undefined”
Hi, I have a problem, that I don’t understand. I am using angular/D3/Typescript in a class that creates a chart. I use d3.evet.clientX and all is well, but in my controller it is undefined. why?
Thanks Mike
IE9 has just offered this pair of doozies with absolutely no reference to whatever the issue is, so 7,000 possible lines of code to sift through. Fun :-|
Not a js error though,
fixed the issue. Head banging time finished.
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
Even though included necessary files am following error
“{Uncaught TypeError: Cannot read property ‘encode’ of undefined}”
am trying to create front end code editor for python mode but couldn’t make it. have had following this example to compile and execute the code.
“http://qnimate.com/create-an-frontend-editor-with-code-highlighting-and-execution/”
could anyone help me to fix it?
Looking forward
A look at this error would help
Thanks, Aldo
After getting tons of undefined is not an object error just surfing (I gave up on programming in 1965 in the SPS IBM 1620 era) I gave up and decided to find out what I was doing wrong. Thanks for a clear explanation that even an over the hill brain can understand. Good to know the problem isn’t all me ;-)
Getting XML5686: Unspecified XML error while getting response. When response XML huge in IE11. Is their any resolution.
Another strange JS error:
Uncaught (in promise) , pointing to the first empty (!) line of my document
Then, after A LOT of debugging, I realised that it’s caused by an unhandled Promise, rejected by an empty string!
If this isn’t confusing, what is?
Maybe it is cause of uncaught rejection with any parameter?) You should always write caught handler with promises.
where is the problem?
The snippet above resulting error below in the handler function ;-( TypeError: callback is not a function
Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!
Uncaught syntaxerror invalid left-hand side in assignment
The uncaught syntaxerror invalid left-hand side in assignment is an error message that is frequently encountered while working with JavaScript.
This error message is easy to fix however, if you’re not familiar with you’ll get confused about how to resolve it.
Fortunately, in this article, we’ll delve into the causes of this syntaxerror and solutions for the invalid left-hand side in assignment expression .
What is uncaught syntaxerror “invalid left-hand side in assignment”?
Here’s another one:
In addition to that, this error message typically indicates that there is a problem with the syntax of an assignment statement.
Why does the “invalid left-hand side in assignment” syntaxerror occur?
It is because you are using a single equal = sign rather than a double == or triple sign ===.
How to fix the “uncaught syntaxerror invalid left-hand side in assignment”?
To fix the uncaught syntaxerror invalid left hand side in assignment expression error, you need to identify where the unexpected assignment is happening in your code.
Solution 1: Use double equals (==) or triple equals (===) when comparing values in JavaScript
Incorrect code:
Solution 2: Use correct operator for string concatenation
Corrected code:
In conclusion, the error message uncaught syntaxerror invalid left-hand side in assignment expression happens in JavaScript when you make an unexpected assignment somewhere.
To fix this error, you need to identify where the unexpected assignment is happening in your code and ensure that you are using the correct operator for the intended operation.
This article already provides solutions to fix this error message. By executing the solutions above, you can master this SyntaxError with the help of this guide.
Leave a Comment Cancel reply
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
"Uncaught ReferenceError: Invalid left-hand side in assignment" when building with certain dependencies #45
gnestor commented Nov 30, 2016
I'm working on a mimerender extension that depends on . When building the extension for notebook, everything works as expected. However, when building for lab, the webpack builds successfully, but when I load it fails with: It points to this line: // __webpack_public_path__ /******/ 'labextension/jupyterlab_table/' = "";`Context of that line: jupyter.define('[email protected]/dist/react-data-grid.js', function (module, exports, __jupyter_require__) { (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(__jupyter_require__('[email protected]/react.js'), __jupyter_require__('[email protected]/index.js')); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["ReactDataGrid"] = factory(require("react"), require("react-dom")); else root["ReactDataGrid"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_2__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __jupyter_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __jupyter_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __jupyter_require__.m = modules; /******/ // expose the module cache /******/ __jupyter_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ 'labextension/jupyterlab_table/' = ""; /******/ // Load entry module and return exports /******/ return __jupyter_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __jupyter_require__) {I should also mention that the built/dist version of reat-data-grid that's downloaded from npm has a similar line: // __webpack_public_path__ /******/ __webpack_require__.p = "";And it's webpack config: I discovered another issue similar to this one: |
The text was updated successfully, but these errors were encountered: |
- 👍 1 reaction
blink1073 commented Nov 30, 2016
So the source is ES6 and you are requiring the entry point directly? It looks like we need to recognize a file that is already a WebPack bundle and special case it. |
Sorry, something went wrong.
This component (and several others that I've seen) distribute a webpack bundle via npm (no source). In this case, you can't even see the build unless you npm install it bc it's gitignored. I think you're right that the issue is that we're bundling a webpack bundle because some others that I've tried were built using just babel and worked fine. To reiterate, I am not having issues with the notebook webpack config, which looks like: entry: './src/index.js', output: { filename: 'index.js', path: '../jupyterlab_table/static', libraryTarget: 'amd' }, devtool: 'source-map', module: { loaders: [ { test: /\.json$/, loader: 'json-loader' }, { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['latest', 'stage-0', 'react'] } }, { test: /\.css$/, loader: 'style-loader!css-loader' } ], } }And here is my : ({ name: 'jupyterlab_table', entry: './src/plugin.js', outputDir: '../jupyterlab_table/static', useDefaultLoaders: false, config: { module: { loaders: [ { test: /\.html$/, loader: 'file-loader' }, { test: /\.(jpg|png|gif)$/, loader: 'file-loader' }, { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' }, { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff' }, { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=application/octet-stream' }, { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader' }, { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10000&mimetype=image/svg+xml' }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['latest', 'stage-0', 'react'] } } ] } } }); |
, does making the following manual change in your fix it? index 7526b9b..acf79cd 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -174,8 +174,8 @@ class JupyterLabPlugin { } // Handle public requires. - let requireP = '__webpack_require__.p'; - let newRequireP = `'${publicPath}'`; + let requireP = '__webpack_require__.p +'; + let newRequireP = `'${publicPath}' + `; source = source.split(requireP).join(newRequireP); // Replace the require name with the custom one. |
Tried that and now I'm getting at: // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __jupyter_require__);The is still in the resulting bundle... |
blink1073 commented Dec 1, 2016
Can you point me to the source repo so I can play with it? |
gnestor commented Dec 1, 2016 • edited Loading
Here ya go: You should be able to set up with . Let me know if you need help... |
gnestor commented Dec 5, 2016
Closed by |
No branches or pull requests
- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- English (US)
- Português (do Brasil)
このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。
ReferenceError: invalid assignment left-hand side
JavaScript の例外 "invalid assignment left-hand side" は、どこかで予想外の代入が行われたときに発生します。例えば、単一の " = " の記号が " == " や " === " の代わりに使用された場合です。
ReferenceError 。
どこかに予想外の代入があります。たとえば、 代入演算子 と 等値演算子 が合っていないからかもしれません。 " = " 記号が 1 つの場合は変数に値を割り当てる一方、" == " か " === " 演算子は値を比較します。
if 文では、等価演算子 ("==") が必要ですし、文字連結にはプラス ("+") 演算子が必要です。
Kickstart your career 🚀 with our new Career Toolbox + automate your job search with Loopcv ⚡
🤖 Our latest AI course Supercharge Your Figma Workflow with AI Plugins , is all yours! Check it out.
Start your #100DaysOfCode challenge here .
Join our free community Discord server here!
Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here .
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
![uncaught referenceerror invalid left hand side in assignment at object success uncaught referenceerror invalid left hand side in assignment at object success](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
- Watch Video
JavaScript AngularJS Basics (1.x) Improving Our Todo App Create a Custom Directive For “todos”
![uncaught referenceerror invalid left hand side in assignment at object success Ana Weller](https://secure.gravatar.com/avatar/4a142cb987eb216970e9744479c59851?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Uncaught ReferenceError: Invalid left-hand side in assignment
I'm getting this error and the todos wont render. The error points to line 30 in main.js
Here is the entire main.js file:
Here is my todos.js file:
And my todos.html file:
And finally my index.html file:
Any suggestions for my code?
![uncaught referenceerror invalid left hand side in assignment at object success Steven Parker](https://uploads.teamtreehouse.com/production/profile-photos/969492/micro_tool_chess_set_2.jpg)
Steven Parker
It looks like you mixed in some stray html code as your argument..
The final workspace code has that line written this way:
Posting to the forum is only allowed for members with active accounts. Please sign in or sign up to post.
- 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.
Uncaught ReferenceError: Invalid left-hand side in assignment
I have an if condition to validate a user input with java script i had and error in this line
- Note : its not a duplicate because the question don't match my case – Maroxtn Commented Dec 25, 2014 at 17:31
3 Answers 3
![uncaught referenceerror invalid left hand side in assignment at object success Rishi Prakash's user avatar](https://lh3.googleusercontent.com/-4RshOz-jU9c/AAAAAAAAAAI/AAAAAAAAASc/u99eiKJDXg0/photo.jpg?sz=64)
You shoud compare with == or === operators not with single =. That is your error.
In if condition you either use == to compare values or === to compare type and value both. In your case you just used one =. So the correct code would be
- This is not true at all, in javascript not always == is used in if condition, === is used too for value and type match. – Marcos González Commented Dec 25, 2014 at 17:48
- @MarcosGonzález But still it's true and it solves the problem. – Rishi Prakash Commented Dec 25, 2014 at 17:51
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 or ask your own question .
- Featured on Meta
- Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
- Announcing a change to the data-dump process
- What makes a homepage useful for logged-in users
Hot Network Questions
- How do you cite an entire magazine/periodical?
- Minhag not to have the moon shine on a sleeping person?
- In Psalm 146:4, what is the correct word--thoughts or plans?
- Is there any way for a character to identify another character's class?
- Why doesn't Cobb want to shoot Mal when she is about to kill Fischer?
- How to Series Expand an Expression in Mathematica with Smaller Cross Terms Compared to Diagonal Terms?
- What is the difference between "the problem about", "the problem of", and "the problem with”?
- Is this an umlaut above a y in this 1922 Patronatsschein?
- Does Event Viewer have any sensitive information like password, or such info?
- Applying a voltage by DAC to a Feedback pin of a DC-DC controller
- One hat's number is the sum of the other 2. How did A figure out his hat number?
- Short story about a boy who meets a dwarf in his garden, travels to a parallel world where people become mist and rescues his mom
- ELI5: If SSL encrypts traffic, why does it expire?
- Diagonal ice tunneling rover to reach a safe pressure in Mars?
- If a unitary operator is close to the identity, will it leave any state it acts on unchanged?
- What hidden class abilities are there in D&D 5e?
- High frequency digital (2GHz+) and PCB manufacturability with FR4?
- Why is my answer incorrect? (Indexed Sets)
- How can I prevent my fountain's water from turning green?
- Variety without a compactification whose complement is smooth
- Sci-Fi book series where a man awakens to find his brain inside a space probe launched into space
- Is there anyway a layperson can discern what is true news vs fake news?
- Double dequer sort
- How to name uppercase variables when using the camelCase convention?
![](http://writinghelp.online/777/templates/cheerup/res/banner1.gif)
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 ...
Uncaught ReferenceError: Invalid left-hand side in an assignment at index.js:25 SyntaxError: Invalid left-hand side in assignment at ESMLoader.moduleStrategy (node: ... # Use bracket notation for object properties that contain hyphens.
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 ...
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.
// Incorrect (trying to modify constant) const PI = 3.14159; PI = 22.7; // Error: Invalid assignment left-hand side // Correct (declare another variable if needed) let radius = 5; let area = PI * radius * radius;
There are two main situations that cause an "Invalid Assignment Left-Hand Side" error: 1. Attempting to Mutate an Immutable Constant ... Uncaught ReferenceError: Invalid left-hand side in assignment at myScript.js:2. ... being able to efficiently interact with the DOM (Document Object Model) using JavaScript is a crucial skill.…
Today we examine the invalid assignment error, which is thrown, as the name implies, when code attempts to perform an invalid assignment somewhere.
SyntaxError: Invalid left-hand side in assignment (V8-based) SyntaxError: invalid assignment left-hand side (Firefox) SyntaxError: Left side of assignment is not a reference. ... // ReferenceError: invalid assignment left-hand side. In the if statement, you want to use an equality operator (===), and for the string concatenation, ...
As for fixing your code in general, that is outside of the scope. I can help you with some guesses: You can set the .innerHTML of the element to the value like follows:. document.getElementById("nprincipal").innerHTML = (principal[0].value*principal_p)/100;
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.
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.
Uncaught ReferenceError: Invalid left-hand side in assignment. Related errors: Uncaught exception: ReferenceError: Cannot assign to 'functionCall()', Uncaught exception: ... The message "left-hand side in assignment" is referring to the part on the left side of the equals sign, so like you can see in the above example, the left-hand ...
The JavaScript exception invalid assignment left-hand side usually occurs when there was an unexpected assignment. It is because you are using a single equal = sign rather than a double == or triple sign ===. Invalid assignments don't always produce syntax errors. Sometimes the syntax is almost correct, but at runtime, the left-hand side ...
aos.css:1 Uncaught ReferenceError: Invalid left-hand side in assignment #16. Closed ... 2016 · 8 comments Closed aos.css:1 Uncaught ReferenceError: Invalid left-hand side in assignment #16. nathanaelphilip opened this issue Jun 13, 2016 · 8 comments Labels. question unconfirmed. Comments. Copy link nathanaelphilip commented Jun 13, 2016.
I have no experience with webpack and cannot put the effort into it to support it. However, if you find a fix for this, please create a PR.
Thanks @micha. It would be better to associate a single click handler with the containing div instead of having one on every span, then give each span an id or data-company attribute or something which the click handler could retrieve to select the appropriate phrase from.
When building the extension for notebook, everything works as expected. However, when building for lab, the webpack builds successfully, but when I load it fails with: Uncaught ReferenceError: Invalid left-hand side in assignment. It points to this line: /*****/
JavaScript の例外 "invalid assignment left-hand side" は、どこかで予想外の代入が行われたときに発生します。例えば、単一の "=" の記号が "==" や "===" の代わりに使用された場合です。
1. you are trying to change the character of an empty string at line no:28 [replaced.charAt (k) = original.charAt (i)] this is the issue. Also there are some unwanted increment in the code. please find the corrected below. I have updated the code below with // comment the code and added correct code. its working.
🙏 Thank you CodeForward sponsor, Tower—the best Git client out there!
Uncaught ReferenceError: Invalid left-hand side in assignment javascript; Share. Improve this question. Follow asked Dec 25, 2014 at 17:31. Maroxtn Maroxtn. 691 4 4 gold ... Invalid left-hand side in assignment : Uncaught ReferenceError: 0. ReferenceError: Invalid left-hand side in assignment JavaScript ...