• View all errors
  • JSLint errors
  • JSHint errors
  • ESLint errors
  • View all options
  • JSLint options
  • JSHint options
  • ESLint options

Bad assignment

This warning has existed in two forms across the three main linters. It was introduced in the original version of JSLint and has remained in all three tools ever since.

In JSLint and JSHint the warning given has always been "Bad assignment"

In ESLint the warning has always been "Invalid left-hand side in assignment"

The situations that produce the warning have not changed despite changes to the text of the warning itself.

When do I get this error?

The "Bad assignment" error (and the alternative "Invalid left-hand side in assignment" error) are thrown when JSLint, JSHint or ESLint encounters an assignment expression in which the left-hand side is a call expression . In the following example we have an if statement with an assignment expression where you would normally expect a conditional:

JSLint also raises this warning when it encounters an assignment to a property of the arguments object . In this example we attempt to define an x property:

Why do I get this error?

In the case of assignment to a function call this error is raised to highlight a fatal reference error . Your code will throw an error in all environments if you do not resolve this issue. It makes no sense to assign a value to a call expression. The return value will be a literal value (such as a string or number) or an object reference, neither of which can be directly assigned to. Imagine it as if you're trying to do 123 = 234 .

If you're receiving the warning in this situation the chances are you were actually trying to perform a comparison rather than an assignment. If that's the case just ensure you're using a comparison operator such as === instead of the assignment operator = :

In the case of assignment to a property of an arguments object this error is raised to highlight a bad practice . The arguments object is notoriously difficult to work with and has behaviour that differs significantly between "normal" and "strict" mode. JSLint has numerous warnings related to abuse of the arguments object but if you're receiving the "Bad assignment" error the chances are you can use a normal variable instead:

In JSHint 1.0.0 and above you have the ability to ignore any warning with a special option syntax . Since this message relates to a fatal reference error you cannot disable it.

In ESLint this error is generated by the Esprima parser and can therefore not be disabled.

About the author

This article was written by James Allardice, Software engineer at Tesco and orangejellyfish in London. Passionate about React, Node and writing clean and maintainable JavaScript. Uses linters (currently ESLint) every day to help achieve this.

Follow me on Twitter  or  Google+

This project is supported by orangejellyfish , a London-based consultancy with a passion for JavaScript. All article content is available on GitHub under the Creative Commons Attribution-ShareAlike 3.0 Unported licence.

Have you found this site useful?

Please consider donating to help us continue writing and improving these articles.

Darren Jones

A Guide to Variable Assignment and Mutation in JavaScript

Share this article

A Guide to Variable Assignment and Mutation in JavaScript

Variable Assignment

Variable reassignment, variable assignment by reference, copying by reference, the spread operator to the rescue, are mutations bad, frequently asked questions (faqs) about javascript variable assignment and mutation.

Mutations are something you hear about fairly often in the world of JavaScript, but what exactly are they, and are they as evil as they’re made out to be?

In this article, we’re going to cover the concepts of variable assignment and mutation and see why — together — they can be a real pain for developers. We’ll look at how to manage them to avoid problems, how to use as few as possible, and how to keep your code predictable.

If you’d like to explore this topic in greater detail, or get up to speed with modern JavaScript, check out the first chapter of my new book Learn to Code with JavaScript for free.

Let’s start by going back to the very basics of value types …

Every value in JavaScript is either a primitive value or an object. There are seven different primitive data types:

  • numbers, such as 3 , 0 , -4 , 0.625
  • strings, such as 'Hello' , "World" , `Hi` , ''
  • Booleans, true and false
  • symbols — a unique token that’s guaranteed never to clash with another symbol
  • BigInt — for dealing with large integer values

Anything that isn’t a primitive value is an object , including arrays, dates, regular expressions and, of course, object literals. Functions are a special type of object. They are definitely objects, since they have properties and methods, but they’re also able to be called.

Variable assignment is one of the first things you learn in coding. For example, this is how we would assign the number 3 to the variable bears :

A common metaphor for variables is one of boxes with labels that have values placed inside them. The example above would be portrayed as a box containing the label “bears” with the value of 3 placed inside.

variables like a box

An alternative way of thinking about what happens is as a reference, that maps the label bears to the value of 3 :

variables like a reference

If I assign the number 3 to another variable, it’s referencing the same value as bears:

variables referencing the same value

The variables bears and musketeers both reference the same primitive value of 3. We can verify this using the strict equality operator, === :

The equality operator returns true if both variables are referencing the same value.

Some gotchas when working with objects

The previous examples showed primitive values being assigned to variables. The same process is used when assigning objects:

This assignment means that the variable ghostbusters references an object:

variables referencing different objects

A big difference when assigning objects to variables, however, is that if you assign another object literal to another variable, it will reference a completely different object — even if both object literals look exactly the same! For example, the assignment below looks like the variable tmnt (Teenage Mutant Ninja Turtles) references the same object as the variable ghostbusters :

Even though the variables ghostbusters and tmnt look like they reference the same object, they actually both reference a completely different object, as we can see if we check with the strict equality operator:

variables referencing different objects

When the const keyword was introduced in ES6, many people mistakenly believed that constants had been introduced to JavaScript, but this wasn’t the case. The name of this keyword is a little misleading.

Any variable declared with const can’t be reassigned to another value. This goes for primitive values and objects. For example, the variable bears was declared using const in the previous section, so it can’t have another value assigned to it. If we try to assign the number 2 to the variable bears , we get an error:

The reference to the number 3 is fixed and the bears variable can’t be reassigned another value.

The same applies to objects. If we try to assign a different object to the variable ghostbusters , we get the same error:

Variable reassignment using let

When the keyword let is used to declare a variable, it can be reassigned to reference a different value later on in our code. For example, we declared the variable musketeers using let , so we can change the value that musketeers references. If D’Artagnan joined the Musketeers, their number would increase to 4:

variables referencing different values

This can be done because let was used to declare the variable. We can alter the value that musketeers references as many times as we like.

The variable tmnt was also declared using let , so it can also be reassigned to reference another object (or a different type entirely if we like):

Note that the variable tmnt now references a completely different object ; we haven’t just changed the number property to 5.

In summary , if you declare a variable using const , its value can’t be reassigned and will always reference the same primitive value or object that it was originally assigned to. If you declare a variable using let , its value can be reassigned as many times as required later in the program.

Using const as often as possible is generally considered good practice, as it means that the value of variables remains constant and the code is more consistent and predictable, making it less prone to errors and bugs.

In native JavaScript, you can only assign values to variables. You can’t assign variables to reference another variable, even though it looks like you can. For example, the number of Stooges is the same as the number of Musketeers, so we can assign the variable stooges to reference the same value as the variable musketeers using the following:

This looks like the variable stooges is referencing the variable musketeers , as shown in the diagram below:

variables cannot reference another variable

However, this is impossible in native JavaScript: a variable can only reference an actual value; it can’t reference another variable . What actually happens when you make an assignment like this is that the variable on the left of the assignment will reference the value the variable on the right references, so the variable stooges will reference the same value as the musketeers variable, which is the number 3. Once this assignment has been made, the stooges variable isn’t connected to the musketeers variable at all.

variables referencing values

This means that if D’Artagnan joins the Musketeers and we set the value of the musketeers to 4, the value of stooges will remain as 3. In fact, because we declared the stooges variable using const , we can’t set it to any new value; it will always be 3.

In summary : if you declare a variable using const and set it to a primitive value, even via a reference to another variable, then its value can’t change. This is good for your code, as it means it will be more consistent and predictable.

A value is said to be mutable if it can be changed. That’s all there is to it: a mutation is the act of changing the properties of a value.

All primitive value in JavaScript are immutable : you can’t change their properties — ever. For example, if we assign the string "cake" to variable food , we can see that we can’t change any of its properties:

If we try to change the first letter to “f”, it looks like it has changed:

But if we take a look at the value of the variable, we see that nothing has actually changed:

The same thing happens if we try to change the length property:

Despite the return value implying that the length property has been changed, a quick check shows that it hasn’t:

Note that this has nothing to do with declaring the variable using const instead of let . If we had used let , we could set food to reference another string, but we can’t change any of its properties. It’s impossible to change any properties of primitive data types because they’re immutable .

Mutability and objects in JavaScript

Conversely, all objects in JavaScript are mutable, which means that their properties can be changed, even if they’re declared using const (remember let and const only control whether or not a variable can be reassigned and have nothing to do with mutability). For example, we can change the the first item of an array using the following code:

Note that this change still occurred, despite the fact that we declared the variable food using const . This shows that using const does not stop objects from being mutated .

We can also change the length property of an array, even if it has been declared using const :

Remember that when we assign variables to object literals, the variables will reference completely different objects, even if they look the same:

But if we assign a variable fantastic4 to another variable, they will both reference the same object:

This assigns the variable fantastic4 to reference the same object that the variable tmnt references, rather than a completely different object.

variables referencing the same object

This is often referred to as copying by reference , because both variables are assigned to reference the same object.

This is important, because any mutations made to this object will be seen in both variables.

So, if Spider-Man joins The Fantastic Four, we might update the number value in the object:

This is a mutation, because we’ve changed the number property rather than setting fantastic4 to reference a new object.

This causes us a problem, because the number property of tmnt will also also change, possibly without us even realizing:

This is because both tmnt and fantastic4 are referencing the same object, so any mutations that are made to either tmnt or fantastic4 will affect both of them.

This highlights an important concept in JavaScript: when objects are copied by reference and subsequently mutated, the mutation will affect any other variables that reference that object. This can lead to unintended side effects and bugs that are difficult to track down.

So how do you make a copy of an object without creating a reference to the original object? The answer is to use the spread operator !

The spread operator was introduced for arrays and strings in ES2015 and for objects in ES2018. It allows you to easily make a shallow copy of an object without creating a reference to the original object.

The example below shows how we could set the variable fantastic4 to reference a copy of the tmnt object. This copy will be exactly the same as the tmnt object, but fantastic4 will reference a completely new object. This is done by placing the name of the variable to be copied inside an object literal with the spread operator in front of it:

What we’ve actually done here is assign the variable fantastic4 to a new object literal and then used the spread operator to copy all the enumerable properties of the object referenced by the tmnt variable. Because these properties are values, they’re copied into the fantastic4 object by value, rather than by reference.

variables referencing different objects

Now any changes that are made to either object won’t affect the other. For example, if we update the number property of the fantastic4 variable to 5, it won’t affect the tmnt variable:

Changes don't affect the other object

The spread operator also has a useful shortcut notation that can be used to make copies of an object and then make some changes to the new object in a single line of code.

For example, say we wanted to create an object to model the Teenage Mutant Ninja Turtles. We could create the first turtle object, and assign the variable leonardo to it:

The other turtles all have the same properties, except for the weapon and color properties, that are different for each turtle. It makes sense to make a copy of the object that leonardo references, using the spread operator, and then change the weapon and color properties, like so:

We can do this in one line by adding the properties we want to change after the reference to the spread object. Here’s the code to create new objects for the variables donatello and raphael :

Note that using the spread operator in this way only makes a shallow copy of an object. To make a deep copy, you’d have to do this recursively, or use a library. Personally, I’d advise that you try to keep your objects as shallow as possible.

In this article, we’ve covered the concepts of variable assignment and mutation and seen why — together — they can be a real pain for developers.

Mutations have a bad reputation, but they’re not necessarily bad in themselves. In fact, if you’re building a dynamic web app, it must change at some point. That’s literally the meaning of the word “dynamic”! This means that there will have to be some mutations somewhere in your code. Having said that, the fewer mutations there are, the more predictable your code will be, making it easier to maintain and less likely to develop any bugs.

A particularly toxic combination is copying by reference and mutations. This can lead to side effects and bugs that you don’t even realize have happened. If you mutate an object that’s referenced by another variable in your code, it can cause lots of problems that can be difficult to track down. The key is to try and minimize your use of mutations to the essential and keep track of which objects have been mutated.

In functional programming, a pure function is one that doesn’t cause any side effects, and mutations are one of the biggest causes of side effects.

A golden rule is to avoid copying any objects by reference. If you want to copy another object, use the spread operator and then make any mutations immediately after making the copy.

Next up, we’ll look into array mutations in JavaScript .

Don’t forget to check out my new book Learn to Code with JavaScript if you want to get up to speed with modern JavaScript. You can read the first chapter for free. And please reach out on Twitter if you have any questions or comments!

What is the difference between variable assignment and mutation in JavaScript?

In JavaScript, variable assignment refers to the process of assigning a value to a variable. For example, let x = 5; Here, we are assigning the value 5 to the variable x. On the other hand, mutation refers to the process of changing the value of an existing variable. For example, if we later write x = 10; we are mutating the variable x by changing its value from 5 to 10.

How does JavaScript handle variable assignment and mutation differently for primitive and non-primitive data types?

JavaScript treats primitive data types (like numbers, strings, and booleans) and non-primitive data types (like objects and arrays) differently when it comes to variable assignment and mutation. For primitive data types, when you assign a variable, a copy of the value is created and stored in a new memory location. However, for non-primitive data types, when you assign a variable, both variables point to the same memory location. Therefore, if you mutate one variable, the change is reflected in all variables that point to that memory location.

What is the concept of pass-by-value and pass-by-reference in JavaScript?

Pass-by-value and pass-by-reference are two ways that JavaScript can pass variables to a function. When JavaScript passes a variable by value, it creates a copy of the variable’s value and passes that copy to the function. Any changes made to the variable inside the function do not affect the original variable. However, when JavaScript passes a variable by reference, it passes a reference to the variable’s memory location. Therefore, any changes made to the variable inside the function also affect the original variable.

How can I prevent mutation in JavaScript?

There are several ways to prevent mutation in JavaScript. One way is to use the Object.freeze() method, which prevents new properties from being added to an object, existing properties from being removed, and prevents changing the enumerability, configurability, or writability of existing properties. Another way is to use the const keyword when declaring a variable. This prevents reassignment of the variable, but it does not prevent mutation of the variable’s value if the value is an object or an array.

What is the difference between shallow copy and deep copy in JavaScript?

In JavaScript, a shallow copy of an object is a copy of the object where the values of the original object and the copy point to the same memory location for non-primitive data types. Therefore, if you mutate the copy, the original object is also mutated. On the other hand, a deep copy of an object is a copy of the object where the values of the original object and the copy do not point to the same memory location. Therefore, if you mutate the copy, the original object is not mutated.

How can I create a deep copy of an object in JavaScript?

One way to create a deep copy of an object in JavaScript is to use the JSON.parse() and JSON.stringify() methods. The JSON.stringify() method converts the object into a JSON string, and the JSON.parse() method converts the JSON string back into an object. This creates a new object that is a deep copy of the original object.

What is the MutationObserver API in JavaScript?

The MutationObserver API provides developers with a way to react to changes in a DOM. It is designed to provide a general, efficient, and robust API for reacting to changes in a document.

How does JavaScript handle variable assignment and mutation in the context of closures?

In JavaScript, a closure is a function that has access to its own scope, the scope of the outer function, and the global scope. When a variable is assigned or mutated inside a closure, it can affect the value of the variable in the outer scope, depending on whether the variable was declared in the closure’s scope or the outer scope.

What is the difference between var, let, and const in JavaScript?

In JavaScript, var, let, and const are used to declare variables. var is function scoped, and if it is declared outside a function, it is globally scoped. let and const are block scoped, meaning they exist only within the block they are declared in. The difference between let and const is that let allows reassignment, while const does not.

How does JavaScript handle variable assignment and mutation in the context of asynchronous programming?

In JavaScript, asynchronous programming allows multiple things to happen at the same time. When a variable is assigned or mutated in an asynchronous function, it can lead to unexpected results if other parts of the code are relying on the value of the variable. This is because the variable assignment or mutation may not have completed before the other parts of the code run. To handle this, JavaScript provides several features, such as promises and async/await, to help manage asynchronous code.

Darren loves building web apps and coding in JavaScript, Haskell and Ruby. He is the author of Learn to Code using JavaScript , JavaScript: Novice to Ninja and Jump Start Sinatra .He is also the creator of Nanny State , a tiny alternative to React. He can be found on Twitter @daz4126.

SitePoint Premium

JavaScript Debugging Toolkit: Identifying and Fixing "Invalid assignment left-hand side"

This error arises when you attempt to assign a value to something that cannot be assigned to. JavaScript requires valid "left-hand sides" (targets) for assignments, which are typically variables, object properties, or array elements.

Correct Usage:

  • Declared variables ( var , let , or const )
  • Existing variables
  • Object properties directly (without functions)
  • Array elements using their numerical indices ( myArray[0] = 5 )

Incorrect Usage:

  • Attempting to assign to expressions or values returned by functions
  • Assigning to undeclared variables (causes ReferenceError )
  • Using incorrect keywords or operators (e.g., using = for comparison instead of == or === )

Sample Code:

Precautions:

  • Carefully check variable declaration (using var , let , or const ) to avoid undeclared variable errors.
  • Remember that constants ( const ) cannot be reassigned after declaration.
  • Use == or === for comparisons, not = for assignments.
  • Be mindful of operator precedence (assignment has lower precedence than logical operators like && ).
  • For object properties and array elements, ensure the object or array exists before assignment.
  • ReferenceError: Occurs when trying to assign to an undeclared variable.
  • TypeError: Occurs when trying to assign to a value that cannot be hold a value (e.g., modifying a constant or a returned function value).
  • SyntaxError: Occurs if the code has incorrect syntax issues that prevent parsing.

Key Points:

  • Understand the different assignment operators and when to use them.
  • Declare variables before using them (except var , which has hoisting).
  • Be mindful of object property and array element accessibility.
  • Use strict equality comparison ( === ) or loose equality ( == ) instead of single assignment ( = ) for comparisons.
  • Practice debugging techniques to identify and fix assignment errors.
  • Consider using linters or code analysis tools to catch potential errors early.

By following these guidelines and carefully avoiding incorrect assignment scenarios, you can write clearer, more robust JavaScript code.

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

Beyond Variables: Unveiling the Magic of First-Class Functions in JavaScript

Key characteristics:Interpreted: Code runs directly in the browser without compilation.Dynamically typed: No need to declare variable types beforehand

  • JavaScript Control Flow: Labels vs. Modern Alternatives - What's Right for You?
  • Building Robust Web Applications: Mastering URIs and Encoding in JavaScript
  • Beyond the Basics: Exploring JavaScript's RegExp.@@matchAll for Advanced String Processing

bad assignment javascript

Error-Free BigInt Operations: Best Practices and Precautions in JavaScript

bad assignment javascript

Mastering the Aggregate: Common Pitfalls and Troubleshooting Tricks for AggregateError

Cautions and best practices for working with javascript date.@@toprimitive.

bad assignment javascript

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.

Specifications

Browser compatibility.

An assignment operator assigns a value to its left operand based on the value of its right operand.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

The basic assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x . The other assignment operators are usually shorthand for standard operations, as shown in the following definitions and examples.

Simple assignment operator is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables. See the example.

Addition assignment

The addition assignment operator adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible. See the addition operator for more details.

Subtraction assignment

The subtraction assignment operator subtracts the value of the right operand from a variable and assigns the result to the variable. See the subtraction operator for more details.

Multiplication assignment

The multiplication assignment operator multiplies a variable by the value of the right operand and assigns the result to the variable. See the multiplication operator for more details.

Division assignment

The division assignment operator divides a variable by the value of the right operand and assigns the result to the variable. See the division operator for more details.

Remainder assignment

The remainder assignment operator divides a variable by the value of the right operand and assigns the remainder to the variable. See the remainder operator for more details.

Exponentiation assignment

The exponentiation assignment operator evaluates to the result of raising first operand to the power second operand. See the exponentiation operator for more details.

Left shift assignment

The left shift assignment operator moves the specified amount of bits to the left and assigns the result to the variable. See the left shift operator for more details.

Right shift assignment

The right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the right shift operator for more details.

Unsigned right shift assignment

The unsigned right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the unsigned right shift operator for more details.

Bitwise AND assignment

The bitwise AND assignment operator uses the binary representation of both operands, does a bitwise AND operation on them and assigns the result to the variable. See the bitwise AND operator for more details.

Bitwise XOR assignment

The bitwise XOR assignment operator uses the binary representation of both operands, does a bitwise XOR operation on them and assigns the result to the variable. See the bitwise XOR operator for more details.

Bitwise OR assignment

The bitwise OR assignment operator uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable. See the bitwise OR operator for more details.

Left operand with another assignment operator

In unusual situations, the assignment operator (e.g. x += y ) is not identical to the meaning expression (here x = x + y ). When the left operand of an assignment operator itself contains an assignment operator, the left operand is evaluated only once. For example:

  • Arithmetic operators

Document Tags and Contributors

  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Using promises
  • Iterators and generators
  • Meta programming
  • JavaScript modules
  • Client-side web APIs
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.ListFormat
  • Intl.Locale
  • Intl.NumberFormat
  • Intl.PluralRules
  • Intl.RelativeTimeFormat
  • ReferenceError
  • SharedArrayBuffer
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Array comprehensions
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical operators
  • Object initializer
  • Operator precedence
  • (currently at stage 1) pipes the value of an expression into a function. This allows the creation of chained function calls in a readable manner. The result is syntactic sugar in which a function call with a single argument can be written like this:">Pipeline operator
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for await...of
  • for each...in
  • function declaration
  • import.meta
  • try...catch
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • The arguments object
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: can't access lexical declaration`X' before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: 'x' is not iterable
  • TypeError: More arguments needed
  • TypeError: Reduce of empty array with no initial value
  • TypeError: can't access dead object
  • TypeError: can't access property "x" of "y"
  • TypeError: can't assign to property "x" on "y": not an object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cannot use 'in' operator to search for 'x' in 'y'
  • TypeError: cyclic object value
  • TypeError: invalid 'instanceof' operand 'x'
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • X.prototype.y called on incompatible type
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

Learn the best of web development

Get the latest and greatest from MDN delivered straight to your inbox.

Thanks! Please check your inbox to confirm your subscription.

If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us.

  • Skip to main content
  • Select language
  • Skip to search
  • Destructuring assignment

Unpacking values from a regular expression match

Es2015 version, invalid javascript identifier as a property name.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Description

The object and array literal expressions provide an easy way to create ad hoc packages of data.

The destructuring assignment uses similar syntax, but on the left-hand side of the assignment to define what values to unpack from the sourced variable.

This capability is similar to features present in languages such as Perl and Python.

Array destructuring

Basic variable assignment, assignment separate from declaration.

A variable can be assigned its value via destructuring separate from the variable's declaration.

Default values

A variable can be assigned a default, in the case that the value unpacked from the array is undefined .

Swapping variables

Two variables values can be swapped in one destructuring expression.

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).

Parsing an array returned from a function

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

Ignoring some returned values

You can ignore return values that you're not interested in:

You can also ignore all returned values:

Assigning the rest of an array to a variable

When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:

Note that a SyntaxError will be thrown if a trailing comma is used on the left-hand side with a rest element:

When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

Object destructuring

Basic assignment, assignment without declaration.

A variable can be assigned its value with destructuring separate from its declaration.

The ( .. ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}

NOTE: Your ( ..) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

Assigning to new variable names

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

A variable can be assigned a default, in the case that the value unpacked from the object is undefined .

Setting a function parameter's default value

Es5 version, nested object and array destructuring, for of iteration and destructuring, unpacking fields from objects passed as function parameter.

This unpacks the id , displayName and firstName from the user object and prints them.

Computed object property names and destructuring

Computed property names, like on object literals , can be used with destructuring.

Rest in Object Destructuring

The Rest/Spread Properties for ECMAScript proposal (stage 3) adds the rest syntax to destructuring. Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.

Destructuring can be used with property names that are not valid JavaScript identifiers  by providing an alternative identifer that is valid.

Specifications

Browser compatibility.

[1] Requires "Enable experimental Javascript features" to be enabled under `about:flags`

Firefox-specific notes

  • Firefox provided a non-standard language extension in JS1.7 for destructuring. This extension has been removed in Gecko 40 (Firefox 40 / Thunderbird 40 / SeaMonkey 2.37). See bug 1083498 .
  • Starting with Gecko 41 (Firefox 41 / Thunderbird 41 / SeaMonkey 2.38) and to comply with the ES2015 specification, parenthesized destructuring patterns, like ([a, b]) = [1, 2] or ({a, b}) = { a: 1, b: 2 } , are now considered invalid and will throw a SyntaxError . See Jeff Walden's blog post and bug 1146136 for more details.
  • Assignment operators
  • "ES6 in Depth: Destructuring" on hacks.mozilla.org

Document Tags and Contributors

  • Destructuring
  • ECMAScript 2015
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • function declaration
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

The Real Bad Parts

By @johnkpaul, johnkpaul.com/empirejs, what's bad but not so bad.

from Bad Parts: Appendix B - JavaScript: The Good Parts

  • type coersion
  • continue/switch

How often do these issues come up?

how many with bugs have you wrangled?

The real bad parts

  • difficult concepts to grasp in the javascript language
  • high blog post to understanding ratio
  • what we might understand, but can't easily explain to others
  • How does this work?

How does prototypal inheritance work?

  • How does scope and hoisting work?

5 different ways to set this

"method" call, baseless function call, using apply, constructor with new.

  • => fat arrow

Fat Arrow =>

What on earth is prototypal inheritance.

What is inheritance...really?

Is it classes ?

Is it blueprints ?

Is it super ?

No, none of these

This is what we really care about

Write code once, use in multiple situations

prototypal inheritance makes this easy

don't think about new , super , and extends

don't even think about javascript's prototype property

Prototypal inheritance is about fallbacks

Not all js environments have Object.create

But we have a solution for < IE9

prototype is double speak

  • prototype #1 - property on a function
  • fallbackOfObjectsCreatedWithNew would be better
  • prototype #2 - internal reference of every object
  • ES6 now calls this dunderproto (__proto__)

What does new do?

  • not necessary

Scoping: breaking the principle of least surprise

Only functions can create scope.

  • Coffeescript has do keyword

ES6 adds let

One of these is not like the other, how does hoisting work.

Only easy rule - if there's no name, it's a expression

If there is a name, it depends on context

  • this can be set in 5 6 different ways
  • prototypal inheritance is based on fallbacks
  • only a function can define a new scope (until let)
  • hoisting moves source code around before interpretation
  • depending on who you ask

johnkpaul.com

COMMENTS

  1. Bad Assignment (JavaScript)

    Bad Assignment (JavaScript) Ask Question Asked 1 year, 8 months ago. Modified 1 year, 8 months ago. ... Though the program runs as expected but I get a Bad Assignment warning because I assigned a function to another function so am trying to know if it isn't proper to do so and if there is a better way of doing it.

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

  3. javascript

    0. = is for assignment, == is for value comparison and === is for value and datatype comparison. So you can use == while comparing with the false. But this is not the best practice. We always uses '!' negation operator while converting true to false. var hungry = true; var foodHere = true; var eat = function() {.

  4. javascript

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

  5. JSLint Error Explanations

    JSLint also raises this warning when it encounters an assignment to a property of the arguments object. In this example we attempt to define an x property: function example() { "use strict"; arguments.x = 1; }

  6. Assignment (=)

    The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...

  7. A Guide to Variable Assignment and Mutation in JavaScript

    In JavaScript, variable assignment refers to the process of assigning a value to a variable. For example, let x = 5; Here, we are assigning the value 5 to the variable x. On the other hand ...

  8. Nullish coalescing assignment (??=)

    No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :

  9. ReferenceError: invalid assignment left-hand side

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

  10. Assignment operators

    An assignment operator assigns a value to its left operand based on the value of its right operand.. Overview. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand.That is, x = y assigns the value of y to x.The other assignment operators are usually shorthand for standard operations, as shown in the following definitions and examples.

  11. JavaScript Debugging Toolkit: Identifying and Fixing "Invalid

    By following these guidelines and carefully avoiding incorrect assignment scenarios, you can write clearer, more robust JavaScript code. SyntaxError: invalid assignment left-hand side The JavaScript exception "invalid assignment left-hand side" occurs when there was an unexpected assignment somewhere.

  12. TypeError: invalid assignment to const "x"

    The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable: const obj ...

  13. 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: Bad return or yield. Errors: Called on incompatible type. Errors: Cant access lexical declaration ...

  14. TypeError: invalid assignment to const "x"

    For instance, in case the content is an object, this means the object itself can still be altered. This means that you can't mutate the value stored in a variable: js. const obj = { foo: "bar" }; obj = { foo: "baz" }; // TypeError: invalid assignment to const `obj'. But you can mutate the properties in a variable:

  15. What went wrong? Troubleshooting JavaScript

    Overview: JavaScript first steps; Next ; When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear — this article aims to save you from tearing your hair out over such problems by providing you with some tips on how to find and fix errors in JavaScript programs.

  16. Assignment operators

    The basic assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x. The other assignment operators are usually shorthand for standard operations, as shown in the following definitions and examples. Name. Shorthand operator.

  17. Destructuring assignment

    The ( ..) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration. {a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal. However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2} NOTE: Your ( ..) expression needs to be ...

  18. Javascript: The Real Bad Parts

    thiscan be set in 56 different ways. prototypal inheritance is based on fallbacks. only a function can define a new scope (until let) hoisting moves source code around before interpretation. ES 6 will make all of our lives easier in approximately 8 years. depending on who you ask. Javascript. The Real Bad Parts.

  19. javascript

    @Haeresis: Any issues it might have would be either negligible, or eliminated by compiler reordering on any reasonably modern JS engine. Only thing that might help (profile!) is explicitly testing while ((htmlElement = htmlCollection[--i]) !== undefined), which might give the JS JIT-er enough information to optimize the expression down to a simple pointer comparison, but again, this is a ...

  20. Destructuring assignment

    Unpacking values from a regular expression match. When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if ...

  21. In JavaScript, is chained assignment okay?

    Then, the same reference (which is the result of the assignment expression) is assigned to a. So a and b refer to the same array. In all other cases, you create two individual arrays. By the way: This behavior is quite common and is the same in all C based programming languages. So this is not JavaScript specific.