Optional Chaining for Assignments Lands in Stage 1

Matt Pocock

In TypeScript, if you try to assign to a property of a possibly undefined object, you'll get an error:

'X' is possibly undefined.

You might think that you can use the optional chaining syntax to fix this:

But you end up with an error:

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

This is because optional chaining is only for reading properties (or deleting properties), not for assigning to them.

But today, the optional chaining for assignments proposal has landed in Stage 1 of TC39.

If this proposal gets adopted into JavaScript, the code below will no longer error.

Share this article with your friends

typescript invalid left hand side in assignment expression

Sometimes, Object Property Order Matters self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

Learn why the order you specify object properties in TypeScript matters and how it can affect type inference in your functions.

Matt Pocock

How To Use Corepack self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

Learn how to use corepack to configure package managers in Node.js projects, ensuring you always use the correct one.

typescript invalid left hand side in assignment expression

How To Strongly Type process.env self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

Learn how to strongly type process.env in TypeScript by either augmenting global type or validating it at runtime with t3-env.

typescript invalid left hand side in assignment expression

`any` Considered Harmful, Except For These Cases self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

Discover when it's appropriate to use TypeScript's any type despite its risks. Learn about legitimate cases where any is necessary.

typescript invalid left hand side in assignment expression

No, TypeScript Types Don't Exist At Runtime self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

Learn why TypeScript's types don't exist at runtime. Discover how TypeScript compiles down to JavaScript and how it differs from other strongly-typed languages.

typescript invalid left hand side in assignment expression

This Pattern Will Wreck Your React App's TS Performance self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

Improve React TypeScript performance by replacing type & with interface extends. Boost IDE and tsc speed significantly.

How to fix SyntaxError: invalid assignment left-hand side

typescript invalid left hand side in assignment expression

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 ⚡️

The left-hand side of an arithmetic operation must be type 'any', 'number', 'bigint' or an enum type

avatar

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

banner

# Table of Contents

  • The LEFT-hand side of an arithmetic operation must be type 'any', 'number', 'bigint' or an enum type
  • The RIGHT-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type

# The left-hand side of an arithmetic operation must be type 'any', 'number', 'bigint' or an enum type

The error "The left-hand side of an arithmetic operation must be type 'any', 'number', 'bigint' or an enum type" occurs when you have an arithmetic operation with values that are not of type any , number or enum , e.g. a Date .

To solve the error convert the values to numbers.

Here is an example of how the error occurs.

left hand side of arithmetic operation must be type

When you subtract a Date object from another Date object (in JavaScript), they both get implicitly converted to a number that represents the milliseconds elapsed between January 1st, 1970 and the given date.

# Use the getTime() method when subtracting Date

To solve the error, call the getTime() method when subtracting the dates.

use get time method when subtracting date

The getTime method returns a number that represents the milliseconds between the Unix epoch and the given date.

# The allowed values for arithmetic operations in TypeScript

TypeScript only allows us to do arithmetic operations with values of type any , number , bigint or enum .

The error is caused if you try to use any other types in arithmetic operations like we did with the Date objects.

# Convert the values to Numbers if number is the expected type

If you aren't getting the error when subtracting Date objects, then try converting the left and right-hand sides of the arithmetic operation to numbers.

convert values to numbers if number is expected type

The example shows how we must convert strings to numbers to be able to subtract them.

Had we not converted the strings to numbers, we would have gotten the same error.

This is because we are only able to do arithmetic operations with values of type number , any or enum .

# The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type

The error "The right-hand side of an arithmetic operation must be type 'any', 'number', 'bigint' or enum" occurs when you have an arithmetic operation where the right-hand side is not of type any , number or enum , e.g. a string .

To solve the error convert the right-hand side to a number.

We have an arithmetic operation where the right-hand side is of type string .

However, TypeScript is not happy because it doesn't consider strings a valid left-hand or right-hand side to arithmetic operations.

# Convert the right-hand side value to a number

To solve the error, convert the right-hand side value to a number .

We used the Number() constructor to convert the string to a number.

The error is caused if you try to use any other types in arithmetic operations e.g. a Date object, string , boolean , etc.

# Solve the error when working with Dates

If you got an error when subtracting Date objects, convert them to numbers by calling the built-in getTime() method.

# The logical OR (||) and logical AND (&&) operators

The error often occurs when using the logical AND (&&) operator or the logical OR (||) operator.

The right-hand side of the operator evaluates to false , so we end up subtracting false from 4 , which caused the error.

Since booleans are not a valid right-hand side for arithmetic operations, you have to make sure the value on the right-hand side is a number .

# Additional Resources

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

  • Operator '+' cannot be applied to types 'Number' and number
  • Convert a String to a Number in TypeScript
  • Convert a Number to a String in TypeScript
  • Convert an Enum to a String or a Number in TypeScript
  • Declare Array of Numbers, Strings or Booleans in TypeScript
  • The left-hand side of assignment expression may not be an optional property access

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

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: 

Please Login to comment...

Similar reads.

  • JavaScript-Errors
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Invalid left-hand side in assignment expression

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

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

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

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

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

Edit: Nevermind, I understand now.

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

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

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

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Expressions and operators

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that purely evaluate .

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to 7 .

The expression 3 + 4 is an example of the second type. This expression uses the + operator to add 3 and 4 together and produces a value, 7 . However, if it's not eventually part of a bigger construct (for example, a variable declaration like const z = 3 + 4 ), its result will be immediately discarded — this is usually a programmer mistake because the evaluation doesn't produce any effects.

As the examples above also illustrate, all complex expressions are joined by operators , such as = and + . In this section, we will introduce the following operators:

Assignment operators

Comparison operators, arithmetic operators, bitwise operators, logical operators, bigint operators, string operators, conditional (ternary) operator, comma operator, unary operators, relational operators.

These operators join operands either formed by higher-precedence operators or one of the basic expressions . A complete and detailed list of operators and expressions is also available in the reference .

The precedence of operators determines the order they are applied when evaluating an expression. For example:

Despite * and + coming in different orders, both expressions would result in 7 because * has precedence over + , so the * -joined expression will always be evaluated first. You can override operator precedence by using parentheses (which creates a grouped expression — the basic expression). To see a complete table of operator precedence as well as various caveats, see the Operator Precedence Reference page.

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

For example, 3 + 4 or x * y . This form is called an infix binary operator, because the operator is placed between two operands. All binary operators in JavaScript are infix.

A unary operator requires a single operand, either before or after the operator:

For example, x++ or ++x . The operator operand form is called a prefix unary operator, and the operand operator form is called a postfix unary operator. ++ and -- are the only postfix operators in JavaScript — all other operators, like ! , typeof , etc. are prefix.

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .

There are also compound assignment operators that are shorthand for the operations listed in the following table:

Name Shorthand operator Meaning

Assigning to properties

If an expression evaluates to an object , then the left-hand side of an assignment expression may make assignments to properties of that expression. For example:

For more information about objects, read Working with Objects .

If an expression does not evaluate to an object, then assignments to properties of that expression do not assign:

In strict mode , the code above throws, because one cannot assign properties to primitives.

It is an error to assign values to unmodifiable properties or to properties of an expression without properties ( null or undefined ).

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

Without destructuring, it takes multiple statements to extract values from arrays and objects:

With destructuring, you can extract multiple values into distinct variables using a single statement:

Evaluation and nesting

In general, assignments are used within a variable declaration (i.e., with const , let , or var ) or as standalone statements.

However, like other expressions, assignment expressions like x = f() evaluate into a result value. Although this result value is usually not used, it can then be used by another expression.

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, some JavaScript style guides discourage chaining or nesting assignments . Nevertheless, assignment chaining and nesting may occur sometimes, so it is important to be able to understand how they work.

By chaining or nesting an assignment expression, its result can itself be assigned to another variable. It can be logged, it can be put inside an array literal or function call, and so on.

The evaluation result matches the expression to the right of the = sign in the "Meaning" column of the table above. That means that x = f() evaluates into whatever f() 's result is, x += f() evaluates into the resulting sum x + f() , x **= f() evaluates into the resulting power x ** f() , and so on.

In the case of logical assignments, x &&= f() , x ||= f() , and x ??= f() , the return value is that of the logical operation without the assignment, so x && f() , x || f() , and x ?? f() , respectively.

When chaining these expressions without parentheses or other grouping operators like array literals, the assignment expressions are grouped right to left (they are right-associative ), but they are evaluated left to right .

Note that, for all assignment operators other than = itself, the resulting values are always based on the operands' values before the operation.

For example, assume that the following functions f and g and the variables x and y have been declared:

Consider these three examples:

Evaluation example 1

y = x = f() is equivalent to y = (x = f()) , because the assignment operator = is right-associative . However, it evaluates from left to right:

  • The y on this assignment's left-hand side evaluates into a reference to the variable named y .
  • The x on this assignment's left-hand side evaluates into a reference to the variable named x .
  • The function call f() prints "F!" to the console and then evaluates to the number 2 .
  • That 2 result from f() is assigned to x .
  • The assignment expression x = f() has now finished evaluating; its result is the new value of x , which is 2 .
  • That 2 result in turn is also assigned to y .
  • The assignment expression y = x = f() has now finished evaluating; its result is the new value of y – which happens to be 2 . x and y are assigned to 2 , and the console has printed "F!".

Evaluation example 2

y = [ f(), x = g() ] also evaluates from left to right:

  • The y on this assignment's left-hand evaluates into a reference to the variable named y .
  • The function call g() prints "G!" to the console and then evaluates to the number 3 .
  • That 3 result from g() is assigned to x .
  • The assignment expression x = g() has now finished evaluating; its result is the new value of x , which is 3 . That 3 result becomes the next element in the inner array literal (after the 2 from the f() ).
  • The inner array literal [ f(), x = g() ] has now finished evaluating; its result is an array with two values: [ 2, 3 ] .
  • That [ 2, 3 ] array is now assigned to y .
  • The assignment expression y = [ f(), x = g() ] has now finished evaluating; its result is the new value of y – which happens to be [ 2, 3 ] . x is now assigned to 3 , y is now assigned to [ 2, 3 ] , and the console has printed "F!" then "G!".

Evaluation example 3

x[f()] = g() also evaluates from left to right. (This example assumes that x is already assigned to some object. For more information about objects, read Working with Objects .)

  • The x in this property access evaluates into a reference to the variable named x .
  • Then the function call f() prints "F!" to the console and then evaluates to the number 2 .
  • The x[f()] property access on this assignment has now finished evaluating; its result is a variable property reference: x[2] .
  • Then the function call g() prints "G!" to the console and then evaluates to the number 3 .
  • That 3 is now assigned to x[2] . (This step will succeed only if x is assigned to an object .)
  • The assignment expression x[f()] = g() has now finished evaluating; its result is the new value of x[2] – which happens to be 3 . x[2] is now assigned to 3 , and the console has printed "F!" then "G!".

Avoid assignment chains

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, chaining assignments in the same statement is discouraged .

In particular, putting a variable chain in a const , let , or var statement often does not work. Only the outermost/leftmost variable would get declared; other variables within the assignment chain are not declared by the const / let / var statement. For example:

This statement seemingly declares the variables x , y , and z . However, it only actually declares the variable z . y and x are either invalid references to nonexistent variables (in strict mode ) or, worse, would implicitly create global variables for x and y in sloppy mode .

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:

Comparison operators
Operator Description Examples returning true
( ) Returns if the operands are equal.

( ) Returns if the operands are not equal.
( ) Returns if the operands are equal and of the same type. See also and .
( ) Returns if the operands are of the same type but not equal, or are of different type.
( ) Returns if the left operand is greater than the right operand.
( ) Returns if the left operand is greater than or equal to the right operand.
( ) Returns if the left operand is less than the right operand.
( ) Returns if the left operand is less than or equal to the right operand.

Note: => is not a comparison operator but rather is the notation for Arrow functions .

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:

In addition to the standard arithmetic operations ( + , - , * , / ), JavaScript provides the arithmetic operators listed in the following table:

Arithmetic operators
Operator Description Example
( ) Binary operator. Returns the integer remainder of dividing the two operands. 12 % 5 returns 2.
( ) Unary operator. Adds one to its operand. If used as a prefix operator ( ), returns the value of its operand after adding one; if used as a postfix operator ( ), returns the value of its operand before adding one. If is 3, then sets to 4 and returns 4, whereas returns 3 and, only then, sets to 4.
( ) Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. If is 3, then sets to 2 and returns 2, whereas returns 3 and, only then, sets to 2.
( ) Unary operator. Returns the negation of its operand. If is 3, then returns -3.
( ) Unary operator. Attempts to , if it is not already.

returns .

returns .

( ) Calculates the to the power, that is, returns .
returns .

A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

Operator Usage Description
Returns a one in each bit position for which the corresponding bits of both operands are ones.
Returns a zero in each bit position for which the corresponding bits of both operands are zeros.
Returns a zero in each bit position for which the corresponding bits are the same. [Returns a one in each bit position for which the corresponding bits are different.]
Inverts the bits of its operand.
Shifts in binary representation bits to the left, shifting in zeros from the right.
Shifts in binary representation bits to the right, discarding bits shifted off.
Shifts in binary representation bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer: Before: 1110 0110 1111 1010 0000 0000 0000 0110 0000 0000 0001 After: 1010 0000 0000 0000 0110 0000 0000 0001
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

Expression Result Binary Description

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation). ~x evaluates to the same value that -x - 1 evaluates to.

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of either type Number or BigInt : specifically, if the type of the left operand is BigInt , they return BigInt ; otherwise, they return Number .

The shift operators are listed in the following table.

Bitwise shift operators
Operator Description Example

( )
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, yields -3, because the sign is preserved.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.

Logical operators
Operator Usage Description
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if both operands are true; otherwise, returns .
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if either operand is true; if both are false, returns .
( ) Returns if its single operand that can be converted to ; otherwise, returns .

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator.

The following code shows examples of the || (logical OR) operator.

The following code shows examples of the ! (logical NOT) operator.

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

Note that for the second case, in modern code you can use the Nullish coalescing operator ( ?? ) that works like || , but it only returns the second expression, when the first one is " nullish ", i.e. null or undefined . It is thus the better alternative to provide defaults, when values like '' or 0 are valid values for the first expression, too.

Most operators that can be used between numbers can be used between BigInt values as well.

One exception is unsigned right shift ( >>> ) , which is not defined for BigInt values. This is because a BigInt does not have a fixed width, so technically it does not have a "highest bit".

BigInts and numbers are not mutually replaceable — you cannot mix them in calculations.

This is because BigInt is neither a subset nor a superset of numbers. BigInts have higher precision than numbers when representing large integers, but cannot represent decimals, so implicit conversion on either side might lose precision. Use explicit conversion to signal whether you wish the operation to be a number operation or a BigInt one.

You can compare BigInts with numbers.

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

The shorthand assignment operator += can also be used to concatenate strings.

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .

The comma operator ( , ) evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop. It is regarded bad style to use it elsewhere, when it is not necessary. Often two separate statements can and should be used instead.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:

A unary operation is an operation with only one operand.

The delete operator deletes an object's property. The syntax is:

where object is the name of an object, property is an existing property, and propertyKey is a string or symbol referring to an existing property.

If the delete operator succeeds, it removes the property from the object. Trying to access it afterwards will yield undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

Deleting array elements

Since arrays are just objects, it's technically possible to delete elements from them. This is, however, regarded as a bad practice — try to avoid it. When you delete an array property, the array length is not affected and other elements are not re-indexed. To achieve that behavior, it is much better to just overwrite the element with the value undefined . To actually manipulate the array, use the various array methods such as splice .

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

For the keywords true and null , the typeof operator returns the following results:

For a number or string, the typeof operator returns the following results:

For property values, the typeof operator returns the type of value the property contains:

For methods and functions, the typeof operator returns results as follows:

For predefined objects, the typeof operator returns results as follows:

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them to avoid precedence issues.

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

The in operator returns true if the specified property is in the specified object. The syntax is:

where propNameOrNumber is a string, numeric, or symbol expression representing a property name or array index, and objectName is the name of an object.

The following examples show some uses of the in operator.

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

Basic expressions

All operators eventually operate on one or more basic expressions. These basic expressions include identifiers and literals , but there are a few other kinds as well. They are briefly introduced below, and their semantics are described in detail in their respective reference sections.

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

Suppose a function called validate validates an object's value property, given the object and the high and low values:

You could call validate in each form element's onChange event handler, using this to pass it to the form element, as in the following example:

Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.

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

ReferenceError: Invalid left-hand side in assignment

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

When I enter in the parameters

I get this error code:

"ReferenceError: Invalid left-hand side in assignment"

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

Alexei Levenkov's user avatar

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

3 Answers 3

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

Joseph Silber's user avatar

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

Common reasons for the error:

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

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

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

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

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

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

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

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

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

Left-Hand-Side Expressions

and The Reference Specification Type explaining IsStrictReference:

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

Community's user avatar

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

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

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

Lukasz Dynowski's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

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

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Was BCD a limiting factor on 6502 speed?
  • Have there been any scholarly attempts and/or consensus as regards the missing lines of "The Ruin"?
  • Are both vocal cord and vocal chord correct?
  • Matryoshka doll problem
  • Is it unfair to retroactively excuse a student for absences?
  • Were there engineers in airship nacelles, and why were they there?
  • Does Matthew 7:13-14 contradict Luke 13:22-29?
  • Why depreciation is considered a cost to own a car?
  • Do known physical systems all have a unique time evolution?
  • Can I tell a MILP solver to prefer solutions with fewer fractions?
  • Is the zero vector necessary to do quantum mechanics?
  • Is there any other reason to stockpile minerals aside preparing for war?
  • Is Légal’s reported “psychological trick” considered fair play or unacceptable conduct under FIDE rules?
  • Simple Container Class
  • White grids appears when export GraphicsRow to PDF
  • Do I need to indicate 'solo' for wind/brass instruments in shared staff?
  • How can I take apart a bookshelf?
  • How to fix misaligned objects that look fine in viewport but not in render?
  • What is the meaning of '"It's nart'ral" in "Pollyanna" by Eleanor H. Porter?
  • How to produce this table: Probability datatable with multirow
  • Are there any CID episodes based on real-life events?
  • DSP Puzzle: Advanced Signal Forensics
  • Can you help me to identify the aircraft in a 1920s photograph?
  • Could a transparent frequency-altering material be possible?

typescript invalid left hand side in assignment expression

Navigation Menu

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

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

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

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

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

Already on GitHub? Sign in to your account

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

@lukescott

lukescott commented Mar 27, 2018 • edited Loading

Bug

num: number | undefined num! += 1

No Errors

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

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

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

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

@babel-bot

babel-bot commented Mar 27, 2018

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

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

Sorry, something went wrong.

@hzoo

Successfully merging a pull request may close this issue.

@existentialism

IMAGES

  1. 【typescript踩坑】The left-hand side of an assignment expression may not be

    typescript invalid left hand side in assignment expression

  2. typescript

    typescript invalid left hand side in assignment expression

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

    typescript invalid left hand side in assignment expression

  4. javascript

    typescript invalid left hand side in assignment expression

  5. VITE + VUE3 项目,突然报 Invalid left-hand side in assignment 错误_vue invalid

    typescript invalid left hand side in assignment expression

  6. jQuery : Building HTML table in javascript, getting "ReferenceError

    typescript invalid left hand side in assignment expression

VIDEO

  1. Function Overloads in 4 minutes ✨

  2. Avoid These Typescript Mistakes

  3. C++ Operators & Expression

  4. How To Remember Tilde and Caret in Lockfiles

  5. error in react 18 -andgt The left-hand side of an assignment expression must be a variable or a prop

  6. Banking form filling Error #rrbpo #ibps

COMMENTS

  1. typescript

    The left-hand side of an assignment expression may not be an optional property access.ts(2779) I have created custom pipe where if I get loop through text and search for a word, if word is present in given text I add highlighted class to it so that, I can hilight that word with pink color

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

    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

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

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

  5. Optional Chaining for Assignments Lands in Stage 1

    The left-hand side of an assignment expression may not be an optional property access. But you end up with an error: The left-hand side of an assignment expression may not be an optional property access. This is because optional chaining is only for reading properties (or deleting properties), not for assigning to them.

  6. Getting error TS2364: Invalid left-hand side of assignment expression

    export class Hero { id: number; name: string; } t1:Hero = { id: 1, name: 'Windstorm' }; For the above angular2 type script statement, Im am hitting following error, attached the debug logs npm debu...

  7. Invalid left hand side of assignment #2534

    Invalid left hand side of assignment #2534. Closed basarat opened this issue Mar 27, 2015 · 2 comments · Fixed by #2569. Closed ... 2015 · 2 comments · Fixed by #2569. Labels. Bug A bug in TypeScript Fixed A PR has been merged for this issue. Milestone. TypeScript 1.5. Comments. Copy link Contributor. basarat commented Mar 27, 2015. Broken ...

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

    Typescript : Invalid left-hand side of assignment expression #10697. Closed ... Closed Typescript : Invalid left-hand side of assignment expression #10697. tamilhce opened this issue Aug 11, 2016 · 2 comments Comments. Copy link tamilhce commented Aug 11, 2016. For the angular2 typescrit export class Hero {id: number;

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

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

    SyntaxError: invalid assignment left-hand side or SyntaxError: Invalid left-hand side in assignment Both errors are the same, and they occured when you use the single equal = sign instead of double == or triple === equals when writing a conditional statement with multiple conditions.

  11. Transpiled ES5 has _invalid left-hand side of assignment expression

    TypeScript Version: 1.7.3 Code import { bindable, customElement } from 'aurelia-framework'; @customElement('my-element') export class MyElement { @bindable heading = "Default heading"; } Let me first say that I have discussed this with t...

  12. The left-hand side of an arithmetic operation must be type 'any

    We have an arithmetic operation where the right-hand side is of type string. However, TypeScript is not happy because it doesn't consider strings a valid left-hand or right-hand side to arithmetic operations. # Convert the right-hand side value to a number. To solve the error, convert the right-hand side value to a number.

  13. Errors: Invalid Assignment Left-hand Side

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

  14. Invalid assignment left-hand side

    This JavaScript exception invalid assignment to const occurs if a user tries to change a constant value. Const declarations in JavaScript can not be re-assigned or re-declared. Message: TypeError: invalid assignment to const "x" (Firefox) TypeError: Assignment to constant variable. (Chrome) TypeError: Assignment to const (Edge) TypeError: Redeclara

  15. Invalid left hand side messages are unhelpful #2474

    X = 0; // Invalid left-hand side of assignment expression. A . X ++ ; // The operand of an increment or decrement operator must be a variable, property or indexer.

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

  17. Expressions and operators

    Evaluation example 1. y = x = f() is equivalent to y = (x = f()), because the assignment operator = is right-associative.However, it evaluates from left to right: The assignment expression y = x = f() starts to evaluate.. The y on this assignment's left-hand side evaluates into a reference to the variable named y.; The assignment expression x = f() starts to evaluate.

  18. Invalid left-hand side of assignment expression error when LHS is ES6

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

  19. ReferenceError: Invalid left-hand side in assignment

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

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

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