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

avatar

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

banner

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

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

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

Here is an example of how the error occurs.

left hand side of assignment expression may not be optional property

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

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

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

use if statement as type guard to solve the error

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

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

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

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

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

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

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

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

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

using non null assertion to solve the error

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

# Avoiding the error with a type assertion

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

avoiding the error with type assertion

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

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

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

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

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

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

using logical and operator to get around the error

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

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

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

All other values are truthy.

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

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

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

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

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

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

# Additional Resources

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

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

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

Home Posts Topics Members FAQ

New Member 13897 Recognized Expert Top Contributor For that use .

In general, anything of style containing a ( - ) will work for JavaScript when hyphen is removed and first letter of the second word is made capital.

eg.
background-image -> backgroundImage
border-top -> borderTop


[EDIT]
Glad to know you solved it. Contributor |Select|Wrap|Line Numbers // pass the argument 'true' for css (hyphen-ated) , leave it out or pass 'false' to return camelCase.
Message
 

Sign in to post your reply or Sign up for a free account.

Similar topics

| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use .

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

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

what is the wrong in my code it showing error " Invalid left-hand side in assignment "?

invalid left hand side in assignment expression document getelementbyid

it is showing error Invalid left-hand side in assignment? what is wrong in this code can any once help ?

Community's user avatar

  • 1 Don't submit code in a image- it makes it harder for other users to run that code, or use it in an answer. See the formatting guide . –  battery.cord Commented Mar 24, 2017 at 13:03
  • remove a==1 and similar. it is not needed –  Ashwani Commented Mar 24, 2017 at 14:07

2 Answers 2

The problem is that you have expressions returning true , which you then attempt to assign values.

What you meant to do is:

The switch statement handles the comparisons for you. case 1 is the case where a is equal to 1.

Also, you want to get the element with the id "number", and instead of switch(a) , you want switch(+a) .

martin's user avatar

Problem is with your JavaScript. Syntax for Switch case is wrong. This is how it should be:

JavaScript documentation

Rohit Mourya's user avatar

  • @popoornimapuligadda replace your switch case code with above code. –  Rohit Mourya Commented Mar 24, 2017 at 13:03

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged javascript jquery ..

  • Featured on Meta
  • Upcoming sign-up experiments related to tags

Hot Network Questions

  • Can my grant pay for a conference marginally related to award?
  • Will it break Counterspell if the trigger becomes "perceive" instead of "see"?
  • Using Roy's Lemma and Walras' Law shows that
  • Horizental gradient colored text with a function
  • In "Romeo and Juliet", why is Juliet the "sun"?
  • Relevance of RFC2228
  • Are there several types of mind-independence?
  • Article that plagiarized our paper is still available and gets cited - what to do?
  • Am I getting scammed
  • Is this crumbling concrete step salvageable?
  • What are philosophers doing when they are discussing free will?
  • What was the Nuclear Boy Scout's Eagle Scout Project?
  • Euro2024-inspired scoring problem
  • Integrating a large product of sines
  • In Northern England, what vowel phoneme is used in “can’t”?
  • Is intrinsic spin a quantum or/and a relativistic phenomenon?
  • Is there any piece that can take multiple pieces at once?
  • Does the recommendation to use password managers also apply to corporate environments?
  • Are many figures in a paper considered bad practice?
  • Australian citizen married to dual Australian/Italian citizen wanting to travel Europe for 6 months
  • How fast can you win this (very stupid) game?
  • Story featuring an alien with an exotic sensorium (sonar?) that helps solve a murder
  • Rank of a matrix with trace and determinant zero.
  • "comfortable", but in the conceptual sense

invalid left hand side in assignment expression document getelementbyid

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • JavaScript Error Object Complete Reference

JS Range Error

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

JS Reference Error

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

JS Syntax Error

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

JS Type Error

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

JS Other Errors

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

JS Error Instance

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

JavaScript ReferenceError – Invalid assignment left-hand side

This JavaScript exception invalid assignment left-hand side occurs if there is a wrong assignment somewhere in code. A single “=” sign instead of “==” or “===” is an Invalid assignment.

Error Type:

Cause of the error: There may be a misunderstanding between the assignment operator and a comparison operator.

Basic Example of ReferenceError – Invalid assignment left-hand side, run the code and check the console

Example 1: In this example, “=” operator is misused as “==”, So the error occurred.

Example 2: In this example, the + operator is used with the declaration, So the error has not occurred.

Output: 

Please Login to comment...

Similar reads.

  • JavaScript-Errors
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Ask a Question
  • Code of Conduct

bad evaluation: invalid left-hand side in assignment

invalid left hand side in assignment expression document getelementbyid

Hello guys. Trying to replace style inside passage. Of course i set $images in StoryInit

passage contains this

and i have a link to change it

As a result i have this

But $images changing normally. I took an example from this  answers, but it doesnt work. Please help

  • sugarcube2-21
  • getelementbyid

Please log in or register to answer this question.

invalid left hand side in assignment expression document getelementbyid

The properties of an element's style API are (mostly) in camelCase, not kebab-case.  Thus, you want marginLeft , rather than margin-left .

Alternatively, use jQuery .  For example:

invalid left hand side in assignment expression document getelementbyid

doesnt work too: 

jquery does not give an error, but the value does not change .-.

Please log in or register to add a comment.

Related questions.

  • getElementById dosent work since Sugarcube ver 2.24.0
  • How to keep side by side images from going below each other in a smaller window?
  • How do I have the picture on the left side of a colored box that has a name and text.
  • Is it possible to move HiEv's health bar a little bit higher and to the right side? Sugarcube
  • Error: <<if>>: bad conditional expression in <<if>> clause: Unexpected token )

Most popular tags

  • Send feedback
  • Main Content

invalid left hand side in assignment expression document getelementbyid

  • 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!

Jani Hartikainen

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

An Interview with Eric Meyer

An Interview with Eric Meyer

Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

Create a Sheen Logo Effect with CSS

Create a Sheen Logo Effect with CSS

I was inspired when I first saw Addy Osmani's original ShineTime blog post .  The hover sheen effect is simple but awesome.  When I started my blog redesign, I really wanted to use a sheen effect with my logo.  Using two HTML elements and...

Incredible Demos

Implement the Google AJAX Search API

Implement the Google AJAX Search API

Let's be honest...WordPress' search functionality isn't great. Let's be more honest...no search functionality is better than Google's. Luckily for us, Google provides an awesome method by which we can use their search for our own site: the Google AJAX Search API.

Assign Anchor IDs Using MooTools 1.2

Assign Anchor IDs Using MooTools 1.2

One of my favorite uses of the MooTools JavaScript library is the SmoothScroll plugin. I use it on my website, my employer's website, and on many customer websites. The best part about the plugin is that it's so easy to implement . I recently ran...

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!

ReferenceError: invalid assignment left-hand side

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

ReferenceError .

What went wrong?

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

Typical invalid assignments

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

  • Assignment operators
  • Equality operators

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

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.

Assigning variable to value of a function (Invalid left-hand side in assignment Error)

I started created a simple calculator using javascript that was able to calculate values with basic operators and decimals and everything was working well. I then decided I wanted to expand the calculator so I created a new design for the calculator that included more advanced capabilities and I changed around the variable and function names to make them more easy to understand and now I’m getting an Uncaught ReferenceError: (line labeled below)

I’ve been going back and forth between my old and new code and I can’t figure out why they look similar but aren’t evaluating the same. I’ve looked up some ideas and I’ve seen a couple places that suggest that you can’t assign a variable to the value of a function. But if that’s the case, why did it work the first time and how do I fix the problem now?

I’ve also looked at the above function in the console step by step, with dummy values and it looks like everything is working correctly.

Here’s a link to the original calculator that is working how I expect:

Thanks in advance!

What does fixedExpress contain when it’s evaluated?

When each button is clicked the value gets added to expressStr. ExpressStr holds the whole expression. CalcExpress() takes expressstr and convers special characters to their actual value so the divide special character will get conveyed to / which allows expressStr to get evaluated using eval

That didn’t answer the question that I asked you.

Your absolutely right. My apologies. FixedExpress returns the current expression (a string) with the special characters replaced with their corresponding operator.

I ask you what fixedExpress contains, because that is where your problem is occurring.

With 2+3 for example, what string does fixedExpress contain when the eval statement occurs?

fixedExpress would contain (‘2+3’)

That’s what it should contain, but currently it doesn’t. You need to investigate what’s actually contained in the fixedExpress string value.

I figured it out! FixedExpress was containing (‘2+3=‘). The = sign was throwing everything off. Thank you for guiding me.

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

  • 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 文では、等価演算子 ("==") が必要ですし、文字連結にはプラス ("+") 演算子が必要です。

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Invalid left-hand side in assignment expression

New person here working on a toy problem building a function that converts a string to camelcase anywhere there is a dash or an underscore. I have almost everything worked out except the second to last line of the function where I am trying to change the characters at each index (from my index array) to uppercase before I return the string. The error I am getting is bad assignment from the left side, but I'm not sure why. I've console logged both sides of the assignment and they seem to be doing what I want, but the assignment itself isn't working. Thank you for any help!

Here is the code:

function toCamelCase(str){ var stringArray = str.split(''); var indexArray = []; stringArray.forEach(character => { if (character === '-' || character === '_') { var index = str.indexOf(character); str = str.slice(0, index) + str.slice(index+1) indexArray.push(index); } return character; }) indexArray.forEach(index => {stringArray.splice(index, 1)}); string = stringArray.join(''); indexArray.forEach(index => {string.charAt(index) = string.charAt(index).toUpperCase()}); return string; }

  • variable-assignment

mateotherock's user avatar

  • Possible duplicate of Why does chartAt() cause an "Invalid left-hand side in assignment" error in JavaScript? –  Guilherme Lemmi Commented Apr 27, 2018 at 22:50

4 Answers 4

The problem is with using string.charAt() on the left hand side. That is not possible as you're trying to assign something to the result of a function, all in the same call. Store the value of string.charAt() in an intermediary variable and it should work. Check the code below for a working example, using a slightly different approach:

Guilherme Lemmi's user avatar

Ah thank you both for pointing me in the right direction. Instead of joining it back to a string I took advantage of it being an array already and just looped through that first.

This code worked...

function toCamelCase(str){ var stringArray = str.split(''); var indexArray = []; stringArray.forEach(character => { if (character === '-' || character === '_') { var index = str.indexOf(character); str = str.slice(0, index) + str.slice(index+1) indexArray.push(index); } return character; }) indexArray.forEach(index => {stringArray.splice(index, 1)}); indexArray.forEach(index => {stringArray[index] = stringArray[index].toUpperCase()}); var string = stringArray.join(''); return string; }

For taking an approach by iterating the characters, you could use a flag for the following upper case letter.

function toCamelCase(str) { var upper = false; return str .split('') .map(c => { if (c === '-' || c === '_') { upper = true; return ''; } if (upper) { upper = false; return c.toUpperCase(); } return c; }) .join(''); } console.log(toCamelCase('foo----bar_baz'));

As strange as it sounds what fixed this error was to add ; semicolon at the end of line where the Parsing error: Invalid left-hand side in assignment expression occurred. More context here.

Lukasz Dynowski's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

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

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • The return of Staging Ground to Stack Overflow
  • The 2024 Developer Survey Is Live
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Are there good examples of regular life being theory-laden?
  • Different eigenfunctions are generated if I change the number of eigenfunctions I want to have
  • Are there several types of mind-independence?
  • What was the Nuclear Boy Scout's Eagle Scout Project?
  • How can non-residents apply for rejsegaranti with Nordjyllands Trafikselskab?
  • Horror movie that has a demon hand coming through a mirror
  • How to fridge/reheat stew so it still tastes good?
  • How much time is needed to judge an Earth-like planet to be safe?
  • In general, How's a computer science subject taught in Best Universities of the World that are not MIT level?
  • How are secret encodings not a violation of amateur radio regulations?
  • Estimating effects in the presence of a mediator
  • Would killing 444 billion humans leave any physical impact on Earth that's measurable?
  • I have an active multiple-entry C1 US visa. I also have a Canadian citizenship certificate. Need to travel (not transit) US in 20 days. My options?
  • Is there a name for books in which the narrator isn't the protagonist but someone who know them well?
  • Is this crumbling concrete step salvageable?
  • Bibliographic references: “[19,31-33]”, “[33,19,31,32]” or “[33], [19], [31], [32]”?
  • Euro2024-inspired scoring problem
  • (SDK issues) com.google.android.play:core has added this note for core:1.9.0
  • Going around in circles
  • Why does crossfading audio files in ffmpeg produce just the last input?
  • Do rich parents pay less in child support if they didn't provide a rich lifestyle for their family pre-divorce?
  • Is there any reason to keep old checks?
  • Split Flaps and lift?
  • Morita equivalence of Lie groupoids and isomorphism of differentiable stacks

invalid left hand side in assignment expression document getelementbyid

TutorialMore

Javascript - コンソールの無効な左手割り当てエラー.

コンソールでこのエラーが発生しています。

コードを再確認しましたが、問題が見つかりません

HTMLは次のとおりです。

自分の問題に似た他の質問を読みましたが、このタイプの質問には答えがないようです。

関数をこれに変更します:

something.getElementById(id)= somethingElse

「=」の左側の要素は、関数実行の匿名の結果(getElementById)であるため、値には影響しません。したがって、エラー「割り当ての左側が無効です」。

特に要素のコンテンツを上書きできる関数(アクセサまたはその他)を使用する必要があります。それが .innerHtml が提案された理由です。

  • python 3.x - 無効なフィルターテンプレートエラーDjango 111
  • python - オブジェクトから整数に変換しようとしたときに無効なオブジェクトエラー
  • database - 移行中の無効な構文エラー
  • google chrome - 低速ネットワークが検出されました。コンソール上のnetdnabootstrapcdnエラー
  • xml - @で始まる変数名はエラーの原因になります:無効なトークン@が行Xの列Yで見つかりました
  • javascript - ボタンがクリックされたときにコンソールがエラーを表示する「関数はHTMLInputElementonclickで定義されていません」
  • opencart2.x - UPSエラー:250003無効なアクセスライセンス番号
  • javascript - firebase firestoreにデータを保存中にコンソールでエラーが発生する
  • java - 無効なLocalDate日付に対してエラーをスローします
  • html - PHP 70エラーのセッション配列の割り当て値
  • ruby - twurl apiを使用中のRailsコンソールでのTwitterエラー
  • c++ - 関数として宣言された変数はありませんが、エラー:バイナリ式に対する無効なオペランド
  • javascript - コンソールエラー:「Uncaught SyntaxError:Unexpected token:Learning sprite」
  • excel - テーブルから一意の値を取得しようとしたときの「定数への割り当て」エラー
  • Python変数割り当てインデックスエラー:パルプの範囲外のリストインデックス
  • ng4-autocompleteを角度4で使用する方法は、コンソールでエラーを出します
  • jquery - 「トークン「>」の構文エラー、無効なFunctionExpressionHeader」が表示されるのはなぜですか
  • Create new Apps Script file with the Apps Script API - Apps Script APIを使用して新しいAppsスクリプトファイルを作成します。エラー:無効なJSONペイロードを受信しました
  • python - Django 111:CreateView:無効なフォームは、存在しないオブジェクト属性に対してエラーを発生させます
  • Instagramからのエラー:指定されたaccess_tokenは無効です
  • 前へ codeigniter form_validation with ajax
  • 次へ php - CodeIgniter:ページネーションをクリックした後に入力値を保持する
  • JavaScript/jQueryを含む小さな画面のハンバーガーメニュー
  • javascript - ExpressとNodejsを使用したGoogle Maps API
  • javascript - setTimeout関数を使用したDivの不透明度の変更が機能しない
  • javascript - 未知の数の数の平均を見つける
  • javascript - コードミラー。 htmlmixedモードのlint
  • javascript - 別のタブをブートストラップタブに動的に追加する方法
  • javascript - 移行中のにを表示する
  • javascript - GoogleからのjQueryが正しく読み込まれず、スクリプトが実行されない
  • javascript - オーバーフローによって隠されたアンカーは、フォーカス時にビューに移動します
  • javascript - Javaスクリプトを使用したフォーム検証

COMMENTS

  1. document.getElementById error: Uncaught ReferenceError: Invalid left

    I have a problem using document.getElementbyId. It doesn't show "test" when I open the html file in my browser and I get an error: Uncaught ReferenceError: Invalid left-hand side in assignment. I have tried putting the script tag in various places, but it doesn't work.

  2. javascript

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

  3. SyntaxError: invalid assignment left-hand side

    Invalid assignments don't always produce syntax errors. Sometimes the syntax is almost correct, but at runtime, the left hand side expression evaluates to a value instead of a reference, so the assignment is still invalid. Such errors occur later in execution, when the statement is actually executed. js. function foo() { return { a: 1 }; } foo ...

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

    The engine interprets the single equal sign as an assignment and not as a comparison operator. We use a single equals sign when assigning a value to a variable.

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

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

  6. Uncaught ReferenceError: Invalid left-hand side in assignment

    Thanks. What would be a good strategy to replace this part of the JSFiddle: document.getElementById("uploadBtn").onchange = function { document.getElementById("uploadFile").value = this.value; };

  7. [SOLVED] how to document.getElementById ().style.padding-left

    I can use document.getElementById ().style.XX to everything i need, except with padding-left, as it is separated by a ' - ' and it is not correct to use it as it was supposed to: document.getElementById ('el').style.padding-left = '5px' will throw 'invalid assignment left-hand side', as expected.. Any help please?

  8. what is the wrong in my code it showing error " Invalid left-hand side

    Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site

  9. Invalid assignment left-hand side

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

  10. bad evaluation: invalid left-hand side in assignment

    The properties of an element's style API are (mostly) in camelCase, not kebab-case. Thus, you want marginLeft, rather than margin-left. Alternatively, use jQuery. For example: Error: <<set>>: bad evaluation: Cannot read propery 'style' of null. jquery does not give an error, but the value does not change .-.

  11. JavaScript Errors and How to Fix Them

    var x = document.getElementByID('foo'); ... Uncaught ReferenceError: Invalid left-hand side in assignment. Related errors: Uncaught exception: ReferenceError: ... 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 ...

  12. Errors: Invalid assignment left-hand side

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

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

  14. Logical OR assignment (||=)

    Description. Logical OR assignment short-circuits, meaning that x ||= y is equivalent to x || (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const: js.

  15. Assigning variable to value of a function (Invalid left-hand side in

    I then decided I wanted to expand the calculator so I created a new design for the calculator that included more advanced capabilities and I changed around the variable and function names to make ...

  16. ReferenceError: invalid assignment left-hand side

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

  17. JavascriptでCSSスタイル変更しようとしたら「Uncaught SyntaxError: Invalid left-hand

    Uncaught SyntaxError: Invalid left-hand side in assignment 左側が受け付けないらしいがなぜかわからない。 エラーになってしまってたコードを抜粋するとこちらになります。

  18. Invalid left-hand side in assignment Javascript

    is treated as: ( (xmlhttp.readyState == 4 && xmlhttp.status) = 200) The left hand side isn't a variable or a property, so you can't assign to it. You don't really want to assign to it though. You are trying to compare and you made a typo. xmlhttp.status = 200 should be xmlhttp.status == 200. edited Dec 19, 2016 at 10:55.

  19. Invalid left-hand side in assignment expression

    2. The problem is with using string.charAt () on the left hand side. That is not possible as you're trying to assign something to the result of a function, all in the same call. Store the value of string.charAt () in an intermediary variable and it should work.

  20. javascript

    Uncaught ReferenceError: Invalid left-hand side in assignment at changeFirstDate (script.js:156) at HTMLInputElement.oninput (index.html:97) ... ('input', changeFirstDate); function changeFirstDate() { let firstDate = document.getElementById('typefirstdate').value; document.getElementById('firstDate') = firstDate; } 自分の問題に似た他 ...