JS Reference

Html events, html objects, other references, javascript object.assign(), description.

The Object.assign() method copies properties from one or more source objects to a target object.

Related Methods:

Object.assign() copies properties from a source object to a target object.

Object.create() creates an object from an existing object.

Object.fromEntries() creates an object from a list of keys/values.

Parameter Description
Required.
An existing object.
Required.
One or more sources.

Return Value

Type Description
ObjectThe target object.

Advertisement

Browser Support

Object.assign() is an ECMAScript6 (ES6) feature.

ES6 (JavaScript 2015) is supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Safari 10 Opera 38
May 2016 Apr 2017 Jun 2017 Sep 2016 Jun 2016

Object.assign() is not supported in Internet Explorer.

Object Tutorials

JavaScript Objects

JavaScript Object Definition

JavaScript Object Methods

JavaScript Object Properties

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

How to copy objects in JavaScript: A complete guide

javascript assignment copy

Editor’s note: This post was updated on 23 March 2022 to include updated information for copying objects in JavaScript and TypeScript, including the structured cloning technique.

How To Copy Objects In JavaScript

When working with functional programming, a good rule of thumb is to always create new objects instead of changing old ones. In doing so we can be sure that our meddling with the object’s structure won’t affect some seemingly unrelated part of the application, which in turn makes the entire code more predictable.

How exactly can we be sure that the changes we make to an object do not affect the code elsewhere? Removing the unwanted references altogether seems like a good idea. To get rid of a reference we need to copy all of the object’s properties to a new object. In this article, we’ll examine five techniques we can use to copy objects in JavaScript, as well as when to use each technique. Where applicable, we’ll also demonstrate how to use each technique to copy objects in TypeScript. TypeScript is basically a subset of JavaScript with static typing, but it is the preferred option for some developers. Compared to JavaScript, Typescript is generally easier to read, understand, and debug.

Here are the five JavaScript copy methods that we’ll review:

Shallow copy

  • Merging with the spread operator or Object.assign() function

Structured cloning

A shallow copy of an object will have the same references as the source object from which the copy was made. As a result, when we modify either the source or the copy, we may also cause the other object to change. In other words, we may unintentionally create unexpected changes in the source or copy. It is critical to grasp the difference between selectively modifying the value of a shared property of an existing element and assigning a completely new value to an existing element.

JavaScript offers standard inbuilt object-copy operations for creating shallow copies: Array.from() , Array.prototype.concat() , Array.prototype.slice() , Object.assign() , and Object.create() , spread syntax .

Here’s an example of shallow copy in JavaScript:

Here’s an example of shallow copy in TypeScript. In this example, we copy the object using the spread operator ( … ).

Here’s another example of shallow copy in TypeScript. In this example, we create a new object and copy every property from the source object:

When to use shallow copy

Shallow copy can be used when we’re dealing with an object that only has properties with primitive data types (for example, strings or numbers). If our object contains non-primitive data types (for example, functions or arrays), it may disrupt our program.

A deep copy of an object will have properties that do not share the same references as the source object from which the copy was made. As a result, we can alter either the source or the copy without changing the other object. In other words, making a change to one object will not cause unexpected changes to either the source or copy.

To make deep copies in JavaScript, we use the JSON.stringify() and JSON.parse() methods. First, we convert the object to a JSON string using the JSON.stringify() function. Then, we parse the string with the JSON.parse() method to create a new JavaScript object:

Now, let’s look at how to make a deep copy of an object in TypeScript.

Our first example works recursively. We write a deep function, which checks the type of the argument sent to it and either calls an appropriate function for the argument (if it is an array or an object) or simply returns the value of the argument (if it is neither an array nor an object).

The deepObject function takes all of the keys of an object and iterates over them, recursively calling the deep function for each value.

So, deepArray iterates over the provided array, calling deep for every value in it.

javascript assignment copy

Over 200k developers use LogRocket to create better digital experiences

javascript assignment copy

Now, let’s look at another TypeScript example taking a different approach. Our goal is to create a new object without any reference to the previous one, right? Why don’t we use the JSON object then? First, we stringify the object, then parse the resulting string. What we get is a new object that is totally unaware of its origin.

It’s important to note that in the prior example the methods of the object are retained, but here they are not. Since JSON format does not support functions, they are removed altogether.

When to use deep copy

Deep copy may be used when your object contains both primitive and non-primitive data types. It can also be used anytime you feel the need to update nested objects or arrays.

The Object.assign() function can be used to copy all enumerable own properties from one or more source objects to a target object. This function returns the target object to the newObject variable.

Here’s an example of copying with the Object.assign() function in JavaScript:

Here’s an example of copying by assigning in TypeScript. Here, we just take each source object and copy its properties to the target , which we normally pass as {} in order to prevent mutation.

Here’s another example of copying by assigning in TypeScript. This example is a safe version in which, instead of mutating the target object, we create an entirely new one that we later assign to a variable. This means we don’t need to pass the target argument at all. Unfortunately, this version does not work with the keyword this because this can’t be reassigned.

When to use assigning

The Object.assign() function may be used to replicate an object that is not modified and assign some new properties to an existing object. In the above sample code, we created an empty object, {} , called target , and assigned the properties from the source object.

More great articles from LogRocket:

  • Don't miss a moment with The Replay , a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

The merge method is similar to the assign method, but instead of altering properties in the target, it joins them together. If a value is an array or an object, this function merges the attributes in a recursive manner. There are two ways to merge objects in JavaScript: using the spread operator or the Object.assign() method.

Spread operator

The spread operator, ... , was implemented in ES6 and can be used to merge two or more objects into one new object that will have the properties of the merged objects. If two objects have the same property name, the latter object property will overwrite the former.

Here’s an example of merging with the spread operator in JavaScript:

Now, let’s look at an example of merging in TypeScript.

The function mergeValues accepts two arguments: target and source . If both values are objects we call and return mergeObjects with the aforementioned target and source as arguments. Analogically, when both values are arrays we call and return mergeArrays . If the source is undefined we just keep whatever value was previously there which means we return the target argument. If none of the above applies we just return the source argument.

Both mergeArrays and mergeObjects work the same way: we take the source properties and set them under the same key in the target .

Now all that is left to do is to create a TypeScript merge function:

Object.assign() method

The Object.assign() method can be used to merge two objects and copy the result to a new target. Just like the spread operator, If the source objects have the same property name, the latter object will replace the preceding object.

Here’s an example:

Now, let’s look at another example of merging in Typescript. With this approach, we want to first get all the properties of the source object , even if they are nested three objects deep ,  and save a path to the properties. This will later allow us to set the value at the proper path inside the target object.

A path is an array of strings that looks something like this: [‘firstObject’,‘secondObject’, ‘propertyName’] .

Here’s an example of how this works:

We call the getValue function to get an array of objects that contain paths and values of the properties. If the argument value is null or is not object-like, we can’t go any deeper so we return an object containing the argument value and its path.

Otherwise, if the argument is object-like and not null , we can be sure it is either an array or an object. If it is an array, we call getArrayValues . If it is an object , we call   getObjectValues .

Both getArrayValues and getObjectValues iterate over properties calling getValue for each with the current index / key now appended to the path .

After getting the paths and values of an entire source object we can see that they are deeply nested. Still, we’d like to keep all of them in a single array. This means that we need to flatten the array.

Flattening an array boils down to iterating over each item to check if it is an array. If it is we flatten it and then concat the value to the result array.

Now that we’ve covered how to get the path , let’s consider how to set all these properties in the target object.

Let’s talk about the setAtPath function that we are going to use to set the values at their respective paths. We want to get access to the last property of the path to set the value. To do so, we need to go over the path’s items, its properties’ names, and each time get the property’s value. We start the reduce function with the target object which is then available as the result argument.

Each time we return the value under result[key] it becomes the result argument in the next iteration. This way, when we get to the last item of the path the result argument is the object or array where we set the value.

In our example the result argument, for each iteration, would be: target -> firstObject -> secondObject .

We have to keep in mind that the target might be an empty object whereas sources can be many levels deep. This means we might have to recreate an object’s or an array’s structure ourselves before setting a value.

We set the value at the last item of the path and return the object we started with.

If inside the firstObject there were no secondObject , we would get undefined and then an error if we tried to set undefined[‘property’] . To prevent this, we first check if result[key] exists. If it does not exist, we’ll need to create it  as either an object or as an array. If the type of the next item is a 'number' (effectively an index), then we’ll need to create an array. If it is a string, we’ll create an object.

Now, all that is left to do is to create the merge function which ties everything together.

When to use merging

Merging objects is not a typical practice in JavaScript, but this method enables us to combine object properties, even with very deeply nested objects.

Structured cloning is a new technique for copying objects in JavaScript. It is a global method that uses the structured clone algorithm to create a deep copy of a specified item. Rather than cloning objects, it transfers objects from their original source to a new source where they are no longer accessible in the original source.

This technique may be used with transferable objects , which is a type of object that owns resources. These objects can only be transferred using the original parameter’s transfer value. As a result of the transfer, the original object will be rendered unusable.

In the below example, the code would would transfer Pascal from the passed in value, but not Akunne :

When to use structured cloning

Structured cloning can be useful for cases when you need to asynchronously validate data in a buffer before saving the data. To avoid the buffer being modified before the data is saved, you can clone the buffer and validate that data. This technique can also be useful if you are transferring the data. With structured cloning, any attempts to modify the original buffer will fail, preventing its accidental misuse.

In this article, we discussed five useful techniques to copy an object in JavaScript as well as TypeScript. We use shallow copy when dealing with an object that only has properties with primitive data types (strings or numbers). Deep copy ensures that there are no references to the source object or any of its properties. Assign is a great way to replicate an object or just to assign some new properties to an existing object. Merge allows us to merge properties of objects, even if the objects are deeply nested. Finally, structured cloning allows us to asynchronously validate and transfer object data, which then renders the original object unusable.

Objects are the basic method by which we organize and transmit data in JavaScript. They are represented in TypeScript via object types ( result: object ). Whether you choose to copy objects in JavaScript or TypeScript, hopefully, this guide has provided you with options to consider for multiple use cases. If you are familiar with other techniques for copying objects in JavaScript, please share them in the comments section.

LogRocket : Debug JavaScript errors more easily by understanding the context

Debugging code is always a tedious task. But the more you understand your errors, the easier it is to fix them.

LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to see exactly what the user did that led to an error.

LogRocket records console logs, page load times, stack traces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!

Try it for free .

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • #vanilla javascript

Hey there, want to help make our blog better?

Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

javascript assignment copy

Stop guessing about your digital experience with LogRocket

Recent posts:.

javascript assignment copy

How to display notification badges on PWAs using the Badging API

Ding! You got a notification, but does it cause a little bump of dopamine or a slow drag of cortisol? […]

javascript assignment copy

JWT authentication: Best practices and when to use it

A guide for using JWT authentication to prevent basic security issues while understanding the shortcomings of JWTs.

javascript assignment copy

Auth.js adoption guide: Overview, examples, and alternatives

Auth.js makes adding authentication to web apps easier and more secure. Let’s discuss why you should use it in your projects.

javascript assignment copy

Lucia Auth: An Auth.js alternative for Next.js authentication

Compare Auth.js and Lucia Auth for Next.js authentication, exploring their features, session management differences, and design paradigms.

javascript assignment copy

One Reply to "How to copy objects in JavaScript: A complete guide"

How is spread syntax. is a shallow copy!

Leave a Reply Cancel reply

Home » JavaScript Object Methods » JavaScript Object.assign()

JavaScript Object.assign()

Summary : in this tutorial, you will learn how to use the JavaScript Object.assign() method in ES6.

The following shows the syntax of the Object.assign() method:

The Object.assign() copies all enumerable and own properties from the source objects to the target object. It returns the target object.

The Object.assign() invokes the getters on the source objects and setters on the target. It assigns properties only, not copying or defining new properties.

Using JavaScript Object.assign() to clone an object

The following example uses the Object.assign() method to clone an object .

Note that the Object.assign() only carries a shallow clone, not a deep clone.

Using JavaScript Object.assign() to merge objects

The Object.assign() can merge source objects into a target object which has properties consisting of all the properties of the source objects. For example:

If the source objects have the same property, the property of the later object overwrites the earlier one:

  • Object.assign() assigns enumerable and own properties from a source object to a target object.
  • Object.assign() can be used to clone an object or merge objects .

Object.assign() in JavaScript

In JavaScript, the Object.assign() function copies properties from one or more source objects to a target object. It returns the target object.

Object.assign() is commonly used to shallow copy objects, although the spread operator is generally faster than Object.assign() for shallow copying . Shallow copying is most commonly used in Redux reducers .

Multiple Sources

You can pass multiple source objects to Object.assign() . If there's multiple sources with the same property, the last one in the parameter list wins out.

More Fundamentals Tutorials

  • The `setTimeout()` Function in JavaScript
  • JavaScript Array flatMap()
  • How to Get Distinct Values in a JavaScript Array
  • Check if a Date is Valid in JavaScript
  • Encode base64 in JavaScript
  • Check if URL Contains a String
  • JavaScript Add Month to Date
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Assignment (=)

The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .

An expression specifying the value to be assigned to x .

Return value

The value of y .

Thrown in strict mode if assigning to an identifier that is not declared in the scope.

Thrown in strict mode if assigning to a property that is not modifiable .

Description

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 together:

This is equivalent to:

Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:

Simple assignment and chaining

Value of assignment expressions.

The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.

Unqualified identifier assignment

The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .

Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:

So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.

In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.

Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

Assignment with destructuring

The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.

For more information, see Destructuring assignment .

Specifications

Specification

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Assignment operators in the JS guide
  • Destructuring assignment

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

Unsupported browser

This site was designed for modern browsers and tested with Internet Explorer version 10 and later.

It may not look or work correctly on your browser.

  • Coding Fundamentals

The Best Way to Deep Copy an Object in JavaScript

Kingsley Ubah

In this article, you'll learn what shallow and deep copying are, and the best way to deep copy an object in JavaScript.

Shallow Copying vs. Deep Copying

In a reassignment operation involving primitive data types such as strings, numbers, and booleans, the original variable is copied by JavaScript. 

For example, consider the following code:

x = 3
= x // x is copied into y
++ // y is incremented
.log(y) // now 4
.log(x) // still 3

In this case, the value 3 is copied into y , and then x is disconnected from y . So mutating y does not affect x .

Conversely, with non-primitive data types like arrays and objects, only a reference to the values is passed. So when the copy is mutated, the original also gets mutated. This is also known as shallow copying .

adam = {name: "Adam"};
jason = adam;
.name = "Jason";
.log(adam.name); // outputs "Jason"
.log(jason.name); // outputs "Jason"

If we instead want to copy an object so that we can modify it without affecting the original object, we need to make a deep copy . 

5 Ways to Deep Copy Objects in JavaScript

In JavaScript, we can perform a copy on objects using the following methods:

clear and direct, the default only shallow copies objects
and deep copies nested objects doesn't copy functions
copies the immediate members of an object—including functions doesn't deep copy nested objects
spread operator simple syntax, the preferred way to copy an object doesn't deep copy nested objects
clones nested objects including functions adds an external dependency to your project

These methods all have their pros and cons. Let's take a closer look at each of them.

Shallow Copy an Object by Assignment

You can create a shallow copy of an object by simply assigning the original object to a new variable. 

Consider the following object:

user = {
: "Kingsley",
: 28,
: "Web Developer"

To create a copy of the object user , we assign the object to a new variable like so:

clone = user
.log(user)
.log(clone)

As observed in the console output, we have now copied the object from user into clone .

However, all we did was create a reference to the original object. Whenever we mutate a property in the object clone , we'll also end up mutating the original object ( user ) as we do in the following code:

.age = 30
.log(user)
.log(clone)

So when a non-primitive data type (array or object) is assigned to a new variable, JavaScript makes a shallow copy of the original object.

Copy an Object With JSON.stringify() and JSON.parse()

The JSON.stringify() method takes in an object and creates a JSON string from it. The JSON.parse()  method parses a string and returns a JavaScript object.

We can combine both of these methods to create a copy of an object in the following way:

user = {
: "Kingsley",
: 28,
: "Web Developer"
clone = JSON.parse(JSON.stringify(user))
.log(user)
.log(clone)

When the copy object is mutated, the original object stays the same:

.age = 32
.log(user)
.log(clone)

However, there is one caveat to using this approach: JSON.stringify() does not copy functions.

Suppose we have a method in our object user called incrementAge :

user = {
: "Kingsley",
: 28,
: "Web Developer",
: function() {
.age++

The function will not be available in the copied object. Thus, this method achieves deep copy only if there is no function within the object.

Copy an Object With Object.assign()

Before ES6, Object.assign() was the most popular way to deep copy an object.

user = {
: "Kingsley",
: 28,
: "Web Developer",
: function() {
.age++
clone = Object.assign({}, user) // Copies user into clone

Object.assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.

.age = 32
.log(user)
.log(clone)

However, one thing to remember about Object.assign() is that the method only performs a partial deep copy on objects.

To understand what that means, let's consider the following:

user = {
: "Kingsley",
: 28,
: "Web Developer",
: {
: "Lagos",
clone = Object.assign({}, user)

As observed, we added the location property and passed an object as its value. Now we have a more complex structure that contains a nested object. 

Whenever we mutate a property within the nested object (in clone ), it will also mutate the same property in the original object ( users ). Let's take a look:

.age = 32
.location.city = "New York"
.log(user)
.log(clone)

While the age  property in the original object remained untouched, the city property was mutated by the reassignment operation.

Hence, the Object.assign() method should be used to deep copy objects that have no nested objects. 

The Best Way to Deep Copy in JavaScript: The Spread Operator

Another way to deep copy objects in JavaScript is with the ES6 spread operator. Using the three dots ( ... ) collects all values on the original object into another object.

user = {
: "Kingsley",
: 28,
: "Web Developer"
clone = {...user}
.log(clone);

However, much like with Object.assign() , the spread operator only makes a partial copy. So any object with a nested object will not be deep copied.

To make a complete deep copy with the spread operator, we'll have to write some additional code.

Consider the same user object but with a nested object:

user = {
: "Kingsley",
: 28,
: "Web Developer",
: {
: "Lagos",
clone = {...user}

To avoid mutating the original object, which is user , we must spread the copy object before making direct changes to any of its properties. For any nested object, we must also spread that sub-object before making changes to any of its properties:

= {
clone,
: 32,
: {
clone.location,
: "New York"

Here, we mutated age , which is a top-level property in clone , and city , which is a sub-property.

This time, the spread operation will give a complete deep copy wherein the original object will be unaffected by any mutation on the copy ( clone ).

.log(user)
.log(clone)

Use Lodash cloneDeep() for Deep Copying

Lodash also provides a utility method _.cloneDeep() for deep cloning of objects in JavaScript.  Read more about the method .

As you've seen, there are a number of ways to copy a variable in JavaScript. None of them is perfect for every occasion, so you'll have to be careful to choose the best method for each situation.

To review, here are the methods and their pros and cons.

Kingsley Ubah

  • 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

What is shallow copy and deep copy in JavaScript ?

JavaScript is a high-level, dynamically typed client-side scripting language. JavaScript adds functionality to static HTML pages. Like most other programming languages JavaScript allows supports the concept of deep copy and shallow copy. 

Shallow Copy

A shallow copy occurs when you copy the reference of an object to a new variable. In this process, only the top-level properties are copied, while nested objects or arrays still reference the original memory location. This means that if you change the nested properties in one object, those changes will reflect in the other because they share the same memory reference.

How Shallow Copy Works

When you assign one object to another using the assignment operator (=), a shallow copy is created:

Example: Below is an example of a shallow copy.

javascript assignment copy

Explanation: From the above example, it is seen that when the name of newEmployee is modified, it is also reflected for the old employee object. This can cause data inconsistency. This is known as a shallow copy. The newly created object has the same memory address as the old one.

Hence, any change made to either of them changes the attributes for both. To overcome this problem, a deep copy is used. If one of them is removed from memory, the other one ceases to exist. In a way the two objects are interdependent.

A deep copy, on the other hand, creates a completely independent copy of the object, including all nested objects or arrays. This ensures that changes made to one object do not affect the other. Each object is stored in a separate memory location, making them entirely independent.

Creating a Deep Copy

Now to create a deep copy of an object in JavaScript we use JSON.parse() and JSON.stringify() methods. Let us take an example to understand it better.

Example: Below is the example of deep copy.

javascript assignment copy

Explanation: Here the new object is created using the JSON.parse() and JSON.stringify() methods of JavaScript. JSON.stringify() takes a JavaScript object as an argument and then transforms it into a JSON string. This JSON string is passed to the JSON.parse() method which then transforms it into a JavaScript object.

This method is useful when the object is small and has serializable properties. But if the object is very large and contains certain non-serializable properties then there is a risk of data loss. Especially if an object contains methods then JSON.stringify() will fail as methods are non-serializable. There are better ways to a deep clone of which one is Lodash which allows cloning methods as well.

Limitations of JSON.parse() and JSON.stringify()

While the JSON approach is simple, it has its limitations:

  • Non-Serializable Properties: Functions, undefined, and certain other non-serializable values are lost when using JSON.stringify().
  • Circular References: Objects with circular references will cause JSON.stringify() to throw an error.
  • Date Objects: Dates are converted to strings during the process, losing their original type.

Lodash To Deep Copy

Lodash is a JavaScript library that provides multiple utility functions and one of the most commonly used functions of the Lodash library is the cloneDeep() method. This method helps in the deep cloning of an object and also clones the non-serializable properties which were a limitation in the JSON.stringify() approach.

Code Implementation:

javascript assignment copy

Explanation: Both objects have different properties after the modification. Also, the methods of each object are differently defined and produce different outputs.

Understanding the difference between shallow copy and deep copy in JavaScript is key to managing data safely and effectively. While a shallow copy is simple and quick, it can lead to unintended side effects when dealing with nested objects.

Deep copy, on the other hand, ensures that objects are fully independent, making your code more predictable. Depending on the complexity of your data structure, you can choose between using native JavaScript methods like JSON.parse()/JSON.stringify() or libraries like Lodash for a more robust solution.

Please Login to comment...

Similar reads.

  • Technical Scripter
  • Web Technologies
  • javascript-basics
  • JavaScript-Questions
  • Technical Scripter 2020
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

DEV Community

DEV Community

Nick Scialli (he/him)

Posted on May 8, 2020 • Updated on May 14, 2020

JS Fundamentals: Object Assignment vs. Primitive Assignment

Introduction.

Something I wish I had understood early on in my JavaScript programming career is how object assignment works and how it's different from primitive assignment. This is my attempt to convey the distinction in the most concise way possible!

Learn JS Fundamentals

Looking to learn more JS fundamentals? Consider signing up for my free mailing list !

Primitives vs. Objects

As a review, let's recall the different primitive types and objects in JavaScript.

Primitive types: Boolean, Null, Undefined, Number, BigInt (you probably won't see this much), String, Symbol (you probably won't see this much)

Object types: Object, Array, Date, Many others

How Primitive and Object Assignment Differ

Primitive assignment.

Assigning a primitive value to a variable is fairly staightforward: the value is assigned to the variable. Let's look at an example.

In this case, a is set to the value hello and b is also set to the value hello . This means if we set b to a new value, a will remain unchanged; there is no relationship between a and b .

Object Assignment

Object assignment works differently. Assigning an object to a variable does the following:

  • Creates the object in memory
  • Assigns a reference to the object in memory to the variable

Why is this a big deal? Let's explore.

The first line creates the object { name: 'Joe' } in memory and then assigns a reference to that object to variable a . The second line assigns a reference to that same object in memory to b !

So to answer the "why is this a big deal" question, let's mutate a property of the object assigned to b :

That's right! Since a and b are assigned a reference to the same object in memory, mutating a property on b is really just mutating a property on the object in memory that both a and b are pointing to.

To be thorough, we can see this in action with arrays as well.

This Applies to Function Arguments too!

These assignment rules apply when you pass objects to functions too! Check out the following example:

The moral of the story: beware of mutating objects you pass to functions unless this is intended (I don't think there are many instances you'd really want to do this).

Preventing Unintended Mutation

In a lot of cases, this behavior can be desired. Pointing to the same object in memory helps us pass references around and do clever things. However, this is not always the desired behavior, and when you start mutating objects unintentionally you can end up with some very confusing bugs.

There are a few ways to make sure your objects are unique. I'll go over some of them here, but rest assured this list will not be comprehensive.

The Spread Operator (...)

The spread operator is a great way to make a shallow copy of an object or array. Let's use it to copy an object.

A note on "shallow" copying

It's important to understand shallow copying versus deep copying. Shallow copying works well for object that are only one level deep, but nested object become problematic. Let's use the following example:

We successfully copied a one level deep, but the properties at the second level are still referencing the same objects in memory! For this reason, people have invented ways to do "deep" copying, such as using a library like deep-copy or serializing and de-serializing an object.

Using Object.assign

Object.assign can be used to create a new object based on another object. The syntax goes like this:

Beware; this is still a shallow copy!

Serialize and De-serialize

One method that can be used to deep copy an object is to serialize and de-serialize the object. One common way to do this is using JSON.stringify and JSON.parse .

This does have its downsides though. Serializing an de-serializing doesn't preserve complex objects like functions.

A Deep Copy Library

It's fairly common to bring in a deep copy library to do the heavy lifting on this task, especially if your object has an unknown or particularly deep hierarchy. These libraries are typically functions that perform one of the aforementioned shallow copy methods recursively down the object tree.

While this can seem like a complex topic, you'll be just fine if you maintain awareness about how primitive types and objects are assigned differently. Play around with some of these examples and, if you're up for it, attempt writing your own deep copy function!

Top comments (5)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

thisdotmedia_staff profile image

  • Location Online
  • Joined Nov 28, 2018

Great article Nick! Well-written, clear, and concise. Really appreciate the images and examples to go along with your main points. This will help a number of devs for sure! Thanks for sharing with us :)

alphavader profile image

  • Location Hamburg, Germany
  • Work Senior Frontend Developer at Freelance
  • Joined Mar 27, 2020

Great article, thanks alot!!

caketi profile image

  • Joined Apr 7, 2020

const b = JSON.parse(JSON.serialize(a));

serialize? maybe stringify

rakesh_suryawanshi profile image

  • Work DevOps Architect
  • Joined Jan 27, 2022

fabianaasara profile image

  • Location York
  • Education Self-taught
  • Work Backend Engineer at RotaCloud
  • Joined Mar 6, 2018

Nice work 🤩easily explained! Thanks.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

dansasser profile image

YAML vs JSON - Best Format for Astro, React & AI Projects. A Developers Guide: Part 1

dansasser - Sep 4

ashutoshsarangi profile image

Performance Impact Using Context API

Ashutosh Sarangi - Sep 13

nazislam profile image

How to Share Data Between Components in Angular Without a Parent-Child Relationship

Naz Islam - Aug 31

suesmith profile image

Destructuring assignment

The two most used data structures in JavaScript are Object and Array .

  • Objects allow us to create a single entity that stores data items by key.
  • Arrays allow us to gather data items into an ordered list.

However, when we pass these to a function, we may not need all of it. The function might only require certain elements or properties.

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.

Destructuring also works well with complex functions that have a lot of parameters, default values, and so on. Soon we’ll see that.

Array destructuring

Here’s an example of how an array is destructured into variables:

Now we can work with variables instead of array members.

It looks great when combined with split or other array-returning methods:

As you can see, the syntax is simple. There are several peculiar details though. Let’s see more examples to understand it better.

It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. However, the array itself is not modified.

It’s just a shorter way to write:

Unwanted elements of the array can also be thrown away via an extra comma:

In the code above, the second element of the array is skipped, the third one is assigned to title , and the rest of the array items are also skipped (as there are no variables for them).

…Actually, we can use it with any iterable, not only arrays:

That works, because internally a destructuring assignment works by iterating over the right value. It’s a kind of syntax sugar for calling for..of over the value to the right of = and assigning the values.

We can use any “assignables” on the left side.

For instance, an object property:

In the previous chapter, we saw the Object.entries(obj) method.

We can use it with destructuring to loop over the keys-and-values of an object:

The similar code for a Map is simpler, as it’s iterable:

There’s a well-known trick for swapping values of two variables using a destructuring assignment:

Here we create a temporary array of two variables and immediately destructure it in swapped order.

We can swap more than two variables this way.

The rest ‘…’

Usually, if the array is longer than the list at the left, the “extra” items are omitted.

For example, here only two items are taken, and the rest is just ignored:

If we’d like also to gather all that follows – we can add one more parameter that gets “the rest” using three dots "..." :

The value of rest is the array of the remaining array elements.

We can use any other variable name in place of rest , just make sure it has three dots before it and goes last in the destructuring assignment.

Default values

If the array is shorter than the list of variables on the left, there will be no errors. Absent values are considered undefined:

If we want a “default” value to replace the missing one, we can provide it using = :

Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.

For instance, here we use the prompt function for two defaults:

Please note: the prompt will run only for the missing value ( surname ).

Object destructuring

The destructuring assignment also works with objects.

The basic syntax is:

We should have an existing object on the right side, that we want to split into variables. The left side contains an object-like “pattern” for corresponding properties. In the simplest case, that’s a list of variable names in {...} .

For instance:

Properties options.title , options.width and options.height are assigned to the corresponding variables.

The order does not matter. This works too:

The pattern on the left side may be more complex and specify the mapping between properties and variables.

If we want to assign a property to a variable with another name, for instance, make options.width go into the variable named w , then we can set the variable name using a colon:

The colon shows “what : goes where”. In the example above the property width goes to w , property height goes to h , and title is assigned to the same name.

For potentially missing properties we can set default values using "=" , like this:

Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided.

In the code below prompt asks for width , but not for title :

We also can combine both the colon and equality:

If we have a complex object with many properties, we can extract only what we need:

The rest pattern “…”

What if the object has more properties than we have variables? Can we take some and then assign the “rest” somewhere?

We can use the rest pattern, just like we did with arrays. It’s not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones.

It looks like this:

In the examples above variables were declared right in the assignment: let {…} = {…} . Of course, we could use existing variables too, without let . But there’s a catch.

This won’t work:

The problem is that JavaScript treats {...} in the main code flow (not inside another expression) as a code block. Such code blocks can be used to group statements, like this:

So here JavaScript assumes that we have a code block, that’s why there’s an error. We want destructuring instead.

To show JavaScript that it’s not a code block, we can wrap the expression in parentheses (...) :

Nested destructuring

If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.

In the code below options has another object in the property size and an array in the property items . The pattern on the left side of the assignment has the same structure to extract values from them:

All properties of options object except extra which is absent in the left part, are assigned to corresponding variables:

Finally, we have width , height , item1 , item2 and title from the default value.

Note that there are no variables for size and items , as we take their content instead.

Smart function parameters

There are times when a function has many parameters, most of which are optional. That’s especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, an item list and so on.

Here’s a bad way to write such a function:

In real-life, the problem is how to remember the order of arguments. Usually, IDEs try to help us, especially if the code is well-documented, but still… Another problem is how to call a function when most parameters are ok by default.

That’s ugly. And becomes unreadable when we deal with more parameters.

Destructuring comes to the rescue!

We can pass parameters as an object, and the function immediately destructurizes them into variables:

We can also use more complex destructuring with nested objects and colon mappings:

The full syntax is the same as for a destructuring assignment:

Then, for an object of parameters, there will be a variable varName for the property incomingProperty , with defaultValue by default.

Please note that such destructuring assumes that showMenu() does have an argument. If we want all values by default, then we should specify an empty object:

We can fix this by making {} the default value for the whole object of parameters:

In the code above, the whole arguments object is {} by default, so there’s always something to destructurize.

Destructuring assignment allows for instantly mapping an object or array onto many variables.

The full object syntax:

This means that property prop should go into the variable varName and, if no such property exists, then the default value should be used.

Object properties that have no mapping are copied to the rest object.

The full array syntax:

The first item goes to item1 ; the second goes into item2 , and all the rest makes the array rest .

It’s possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one.

We have an object:

Write the destructuring assignment that reads:

  • name property into the variable name .
  • years property into the variable age .
  • isAdmin property into the variable isAdmin (false, if no such property)

Here’s an example of the values after your assignment:

The maximal salary

There is a salaries object:

Create the function topSalary(salaries) that returns the name of the top-paid person.

  • If salaries is empty, it should return null .
  • If there are multiple top-paid persons, return any of them.

P.S. Use Object.entries and destructuring to iterate over key/value pairs.

Open a sandbox with tests.

Open the solution with tests in a sandbox.

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy
  • 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.

Copy array by value

When copying an array in JavaScript to another array:

I realized that arr2 refers to the same array as arr1 , rather than a new, independent array. How can I copy the array to get two independent arrays?

  • pass-by-value

Penny Liu's user avatar

  • 4 It looks like currently in Chrome 53 and Firefox 48 we have cool performance for slice and splice operations and new spread operator and Array.from have much slower implementation. Look at perfjs.fnfo –  Pencroff Commented Sep 16, 2016 at 13:32
  • jsben.ch/#/wQ9RU <= this benchmark gives an overview over the different ways to copy an array –  EscapeNetscape Commented Oct 24, 2016 at 18:47
  • jsperf.com/flat-array-copy –  Walle Cyril Commented May 25, 2017 at 17:08
  • 42 It's 2017, so you might consider using ES6 features: let arr2 = [...arr1]; developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… –  Hinrich Commented Sep 22, 2017 at 8:30
  • 2 Well when you state a = b; you actually tell the program to point in both cases to a same symbolic link in random access memory. And when a value at this symbolic link is changed it affects a and b ... So if you use a spread operator a= [...b]; program will create an additional symbolic link to a different location in random access memory and you can then manipulate a and b independently. –  71GA Commented Dec 15, 2019 at 20:49

40 Answers 40

let oldArray = [1, 2, 3, 4, 5]; let newArray = oldArray.slice(); console.log({newArray});

Basically, the slice() operation clones the array and returns a reference to a new array.

Also note that:

For references, strings and numbers (and not the actual object), slice() copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.

Teocci's user avatar

  • 9 Regarding performance the following jsPerf tests actually show that var arr2 = arr1.slice() is just as fast as var arr2 = arr1.concat(); JSPerf: jsperf.com/copy-array-slice-vs-concat/5 and jsperf.com/copy-simple-array . The result of jsperf.com/array-copy/5 kind of surprised me to the point I am wondering if the test code is valid. –  Cohen Commented Dec 19, 2012 at 18:46
  • 117 Even though this has already received a ton of upvotes, it deserves another because it properly describes references in JS, which is sort of rare, unfortunately. –  Wayne Commented Jan 20, 2014 at 16:29
  • 38 @GáborImre you'd add an entire library simply for readability? Really? I'd just add a comment if I were that concerned for readability. See: var newArray = oldArray.slice(); //Clone oldArray to newArray –  dudewad Commented Feb 8, 2016 at 19:47
  • 13 @GáborImre I get that, sure. But answering a specific engineering problem by including an entire library in my opinion is not helpful, it's design bloat. I see developers do that a lot, and then you end up with a project that included an entire framework to replace having to write a single function. Just my M.O., though. –  dudewad Commented Feb 9, 2016 at 19:48
  • 15 Lesson learned: Don't confuse .slice() with .splice() , which gives you an empty array. Big difference. –  crazypeter Commented Feb 28, 2018 at 6:20

In Javascript, deep-copy techniques depend on the elements in an array. Let's start there.

Three types of elements

Elements can be: literal values, literal structures, or prototypes.

From these elements we can create three types of arrays.

Deep copy techniques depend on the three array types

Based on the types of elements in the array, we can use various techniques to deep copy.

Deep copy techniques

Javascript deep copy techniques by element types

https://www.measurethat.net/Benchmarks/Show/17502/0/deep-copy-comparison

Array of literal-values (type1) The [ ...myArray ] , myArray.splice(0) , myArray.slice() , and myArray.concat() techniques can be used to deep copy arrays with literal values (boolean, number, and string) only; where slice() has the highest performance in Chrome, and spread ... has the highest performance in Firefox.

Array of literal-values (type1) and literal-structures (type2) The JSON.parse(JSON.stringify(myArray)) technique can be used to deep copy literal values (boolean, number, string) and literal structures (array, object), but not prototype objects.

All arrays (type1, type2, type3)

  • structuredClone() ;
  • The Lo-dash cloneDeep(myArray) or jQuery extend(true, [], myArray) techniques can be used to deep-copy all array-types. Where the Lodash cloneDeep() technique has the highest performance.
  • And for those who avoid third-party libraries, the custom function below will deep-copy all array-types, with lower performance than cloneDeep() and higher performance than extend(true) .

So to answer the question...

I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?

Because arr1 is an array of literal values (boolean, number, or string), you can use any deep copy technique discussed above, where slice() and spread ... have the highest performance.

tim-montague's user avatar

  • 3 Many of these approaches do not work well. Using the assignment operator means that you have to reassign the original literal value of arr1 . It's very rare that that's going to be the case. Using splice obliterates arr1 , so that's not a copy at all. Using JSON will fail if any of the values in the array are Functions or have prototypes (such as a Date ). –  Dancrumb Commented Sep 18, 2014 at 19:53
  • 1 Why splice(0)? Shouldn't it be slice() ? I think it's supposed not to modify original array, which splice does. @JamesMontagne –  helpse Commented May 14, 2015 at 15:29
  • 2 splice will create pointers to the elements in the original array (shallow copy). splice(0) will allocate new memory (deep copy) for elements in the array which are numbers or strings, and create pointers for all other element types (shallow copy). By passing a start value of zero to the splice function-method, it won't splice any elements from the original array, and therefore it doesn't modify it. –  tim-montague Commented May 21, 2015 at 9:35
  • 2 Actually, there is only one type of array: an array of "somethings". There is no difference between [0,"1",{2:3},function random() {return 4;}, [[5,6,7],[8,9,10],[11,12,13]]] and any other array. –  wizzwizz4 Commented Apr 7, 2016 at 9:12
  • 1 IMO these all have bad legibility. The fact that someone is meaning to clone an array is not apparent to me. What is wrong with calling it x.clone() ? –  Jonny Commented May 16, 2022 at 6:25

You can use array spreads ... to copy arrays.

const itemsCopy = [...items];

Also if want to create a new array with the existing one being part of it:

Array spreads are now supported in all major browsers but if you need older support use typescript or babel and compile to ES5.

More info on spreads

Luke Femur's user avatar

  • 8 This won't work for deep copy. Deep Clone an Array in JavaScript . –  SNag Commented Dec 28, 2019 at 18:47
  • 1 Beware that this will also create new entries for "undefined" in the original array. Which might brake your code. –  Krisztián Balla Commented Apr 19, 2022 at 13:15

No jQuery needed... Working Example

This copys the array from the starting position 0 through the end of the array.

It is important to note that it will work as expected for primitive types (string, number, etc.), and to also explain the expected behavior for reference types...

If you have an array of Reference types, say of type Object . The array will be copied, but both of the arrays will contain references to the same Object 's. So in this case it would seem like the array is copied by reference even though the array is actually copied.

jondavidjohn's user avatar

  • 18 No this would not be a deep copy. –  jondavidjohn Commented Oct 14, 2014 at 22:16
  • 1 Try this; var arr2 = JSON.stringify(arr1); arr2 = JSON.parse(arr2); –  pradeep1991singh Commented Dec 19, 2018 at 7:11
  • 4 What's the difference between this answer and the accepted answer? –  Isaac Pak Commented Apr 13, 2019 at 14:04
  • getting error in console for your given example "TypeError: window.addEvent is not a function" –  Ravi Sharma Commented Dec 31, 2019 at 5:42
  • @IsaacPak This was answered 2 mins before that. –  brc-dd Commented Oct 6, 2021 at 16:40

This is how I've done it after trying many approaches:

This will create a new deep copy not related to the first one (not a shallow copy).

Also this obviously will not clone events and functions, but the good thing you can do it in one line, and it can be used for any kind of object (arrays, strings, numbers, objects ...)

Peter Mortensen's user avatar

  • 7 This is the best one. I use the same method a long time ago and think that there is no more sense in old school recursive loops –  Vladimir Kharlampidi Commented May 5, 2014 at 20:28
  • 2 Be aware that this option doesn't handle well graph-like structures: crashes in presence of cycles, and doesn't preserve shared references. –  Ruben Commented Jun 28, 2014 at 23:12
  • 3 This also fails for things like Date , or indeed, anything that has a prototype. In addition, undefined s get converted to null s. –  Dancrumb Commented Sep 18, 2014 at 19:57
  • 10 Is no one brave enough to comment on the gross inefficiency in both CPU and memory of serializing to text and then parsing back to an object? –  L. Cornelius Dol Commented Dec 9, 2014 at 23:58
  • 1 This does a deep copy. The question didn't ask for that. Although it is useful, it does something different than the other answers. –  wizzwizz4 Commented Apr 7, 2016 at 9:15

An alternative to slice is concat , which can be used in 2 ways. The first of these is perhaps more readable as the intended behaviour is very clear:

The second method is:

Cohen (in the comments) pointed out that this latter method has better performance .

The way this works is that the concat method creates a new array consisting of the elements in the object on which it is called followed by the elements of any arrays passed to it as arguments. So when no arguments are passed, it simply copies the array.

Lee Penkman, also in the comments, points out that if there's a chance array1 is undefined , you can return an empty array as follows:

Or, for the second method:

Note that you can also do this with slice : var array2 = (array1 || []).slice(); .

Ninjakannon's user avatar

  • 31 Actually you can also do: var array2 = array1.concat(); It's a lot faster regarding performance. (JSPerf: jsperf.com/copy-simple-array and jsperf.com/copy-array-slice-vs-concat/5 –  Cohen Commented Dec 19, 2012 at 18:50
  • 5 Its worth noting that if array1 isn't an array then [].concat(array1) returns [array1] e.g. if its undefined you'll get [undefined] . I sometimes do var array2 = [].concat(array1 || []); –  lee penkman Commented Aug 1, 2014 at 8:27

Most of answers here works for particular cases .

If you don't care about deep/nested objects and props use ( ES6 ):

let clonedArray = [...array]

but if you want to do deep clone use this instead:

let cloneArray = JSON.parse(JSON.stringify(array)) *

*functions won't be preserved (serialized) while using stringify, you will get result without them.

For lodash users:

let clonedArray = _.clone(array) documentation

let clonedArray = _.cloneDeep(array) documentation

ulou's user avatar

I personally think Array.from is a more readable solution. By the way, just beware of its browser support.

// clone let x = [1, 2, 3]; let y = Array.from(x); console.log({y}); // deep clone let clone = arr => Array.from(arr, item => Array.isArray(item) ? clone(item) : item); x = [1, [], [[]]]; y = clone(x); console.log({y});

Lewis's user avatar

  • 2 Yes, this is very readable. The .slice() solution is completely unintuitive. Thanks for this. –  Banago Commented Jul 27, 2016 at 14:46

Some of mentioned methods work well when working with simple data types like number or string, but when the array contains other objects these methods fail. When we try to pass any object from one array to another it is passed as a reference, not the object.

Add the following code in your JavaScript file:

And simply use

It will work.

sarvesh singh's user avatar

  • 2 i get this error when i add this code to my page 'Uncaught RangeError: Maximum call stack size exceeded' –  sawe Commented Jan 21, 2013 at 17:56
  • 1 My apologies, this error occurs in chrome if arr1 is not declared. so i copy-pasted the above code, and i get the error, however, if i declare the array arr1, then i do not get the error. You could improve the answer by declaring arr1 just above arr2, i see there are quite a few of 'us' out there who did not recognise that we had to declare arr1 (partly because when i was evaluating your answer, i was in a rush and needed something that 'just works') –  sawe Commented Apr 11, 2013 at 5:01
  • .slice() still works fine even if you have objects in your array: jsfiddle.net/edelman/k525g –  Jason Commented May 30, 2013 at 19:49
  • 7 @Jason but the objects are still pointing to the same object so changing one will change the other. jsfiddle.net/k525g/1 –  Samuel Commented Jul 8, 2013 at 14:39
  • Excellent code. One question I have, I actually tried to copy one array into another like this var arr1 = new Array() and then var arr2 = arr1; If I change something in arr2 the change happens also to arr1. However, if I use the clone prototype you made, It actually creates a complete new instance of that array or in other words it copies it. So is this a browser problem? or javascript by default sets the two variables by one pointing to an other with the use of pointers when someone does var arr2=arr1 and why does not happen with integer variables? see jsfiddle.net/themhz/HbhtA –  themhz Commented Aug 11, 2013 at 18:13

From ES2015,

Boopathi Rajaa's user avatar

If you are in an environment of ECMAScript 6 , using the Spread Operator you could do it this way:

var arr1 = ['a','b','c']; var arr2 = [...arr1]; //copy arr1 arr2.push('d'); console.log(arr1) console.log(arr2) <script src="http://www.wzvang.com/snippet/ignore_this_file.js"></script>

Walter Chapilliquen - wZVanG's user avatar

Primitive values are always pass by its value (copied). Compound values however are passed by reference.

So how do we copy this arr?

Copy an Array in ES6

Copy n array in es5, why `let arrcopy = arr` is not passing by value.

Passing one varible to another on Compound values such as Object/Array behave difrently. Using asign operator on copand values we pass reference to an object. This is why the value of both arrays are changing when removing/adding arr elements.

Exceptions:

When you assign a new value to the variable, you are changing the reference itself and it doesn’t affect the original Object/Array.

DevWL's user avatar

Adding to the solution of array.slice(); be aware that if you have multidimensional array sub-arrays will be copied by references. What you can do is to loop and slice() each sub-array individually

same things goes to array of objects, they will be copied by reference, you have to copy them manually

A.Zaben's user avatar

  • This answer deserves a spot near the top of the page! I was working with multidimensional sub arrays and could not follow why the inner arrays were always being copied by ref and not by val. This simple logic solved my problem. I would give you +100 if possible! –  Mac Commented Feb 16, 2017 at 1:33

Now you can do any one of the following to make a copy of an array.

Now, if i change a,

Then, a is [1,2,3,5] but b is still [1,2,3] as it has different reference.

But i think, in all the methods above Array.from is better and made mainly to copy an array.

Nitesh Ranjan's user avatar

  • 1 which one is the fastest? –  Marc Frame Commented Jun 7, 2019 at 2:11

I would personally prefer this way:

GalAbra's user avatar

  • So the way suggested here ? –  Script47 Commented Mar 25, 2019 at 11:55

I found this method comparatively easier:

let arr = [1,2,3,4,5]; let newArr = [...arr]; console.log(newArr);

Supercool's user avatar

  • Has already been answered here (and a bunch of other answers). –  Ivar Commented Sep 6, 2022 at 12:41

You must use best practice for this question when there are a lot of answers.

I recommend to you use array spreads … to copy arrays.

var arr1 = ['a','b','c'];

var arr2 = […arr1];

NimaDoustdar's user avatar

As we know in Javascript arrays and objects are by reference, but what ways we can do copy the array without changing the original array later one?

Here are few ways to do it:

Imagine we have this array in your code:

1) Looping through the array in a function and return a new array, like this:

2) Using slice method, slice is for slicing part of the array, it will slice some part of your array without touching the original, in the slice, if don't specify the start and end of the array, it will slice the whole array and basically make a full copy of the array, so we can easily say:

3) Also contact method, this is for merging two array, but we can just specify one of arrays and then this basically make a copy of the values in the new contacted array:

4) Also stringify and parse method, it's not recommended, but can be an easy way to copy Array and Objects:

5) Array.from method, this is not widely supported, before use check the support in different browsers:

6) ECMA6 way, also not fully supported, but babelJs can help you if you want to transpile:

Alireza's user avatar

You could use ES6 with spread Opeartor, its simpler.

There are limitations..check docs Spread syntax @ mozilla

BluePie's user avatar

Dan, no need to use fancy tricks. All you need to do is make copy of arr1 by doing this.

var arr1 = ['a','b','c']; var arr2 = []; var arr2 = new Array(arr1); arr2.push('d'); // Now, arr2 = [['a','b','c'],'d'] console.log('arr1:'); console.log(arr1); console.log('arr2:'); console.log(arr2); // Following did the trick: var arr3 = [...arr1]; arr3.push('d'); // Now, arr3 = ['a','b','c','d']; console.log('arr3:'); console.log(arr3);

Now arr1 and arr2 are two different array variables stored in separate stacks. Check this out on jsfiddle .

Jürgen Fink's user avatar

  • 3 This doesn't copy the array. It creates an array with one element that references the original (i.e. var arr2 = [arr1]; ). –  Timothy003 Commented Nov 21, 2018 at 23:25
  • @DragoRaptor I hope you don't mind that I edited your answer, completing your snippet code here with your code from jsfiddle, changing document.write(arr2) to console.log(arr2) so that nested array structure would show and better illustrate correct comment from @Timothy003. var arr3 = [...arr1] did the trick, though. Run code snippet to see results. (Output from document.write(arr2) was a bit misleading, hence I don't blame you). –  Jürgen Fink Commented Jul 14, 2021 at 17:35
var arr2 = arr1.slice(0);

This way just work for simple Arrays .

If you have Complex Array like array of Objects then you must use another solutions like:

For example, we have an array of objects that each cell have another array field in its object ... in this situation if we use slice method then the array fields will copy by Ref and that's mean these fields updates will affect on orginal array same element and fields.

Eyni Kave's user avatar

structuredClone

The modern way to copy array by value in JavaScript is to use structuredClone :

var arr1 = ['a', 'b', 'c']; var arr2 = structuredClone(arr1); //copy arr1 arr2.push('d'); console.log(arr1); //a,b,c console.log(arr2); //a,b,c,d

XMehdi01's user avatar

In my particular case I needed to ensure the array remained intact so this worked for me:

fiat's user avatar

  • 2 +1 for not adding obscuity to your code by calling a function that does exactly the same thing, but in a less obvious way. slice may be more efficient under the hood, but to anyone working on the code, this shows your intent. plus it makes it easier to optimise later, if you want to (for example) filter what you are copying. note however this does not handle deep copying, and the same internal objects are passed to the new array, by reference. This might be what you want to do, it might not. –  unsynchronized Commented Jun 30, 2014 at 22:45

Make copy of multidimensional array/object:

Thanks to James Padolsey for this function.

Source: Here

heena Jethva's user avatar

If your array contains elements of the primitive data type such as int, char, or string etc then you can user one of those methods which returns a copy of the original array such as .slice() or .map() or spread operator(thanks to ES6).

BUT if your array contains complex elements such as objects(or arrays) or more nested objects , then, you will have to make sure that you are making a copy of all the elements from the top level to the last level else reference of the inner objects will be used and that means changing values in object_elements in new_array will still affect the old_array. You can call this method of copying at each level as making a DEEP COPY of the old_array.

For deep copying, you can use the above-mentioned methods for primitive data types at each level depending upon the type of data or you can use this costly method(mentioned below) for making a deep copy without doing much work.

There are a lot of other methods out there which you can use depending on your requirements. I have mentioned only some of those for giving a general idea of what happens when we try to copy an array into the other by value .

abhinav1602's user avatar

  • Thanks a lot, your answer was the only one who worked for my scenario, –  albert sh Commented Jun 19, 2019 at 3:07

If you want to make a new copy of an object or array, you must explicitly copy the properties of the object or the elements of the array, for example:

You can search for more information on Google about immutable primitive values and mutable object references.

Sotiris's user avatar

  • 1 You don't have to explicitly copy the properties of the objects of the array. See Chtiwi Malek's answer. –  Magne Commented Jun 4, 2014 at 14:30

When we want to copy an array using the assignment operator ( = ) it doesn't create a copy it merely copies the pointer/reference to the array. For example:

const oldArr = [1,2,3]; const newArr = oldArr; // now oldArr points to the same place in memory console.log(oldArr === newArr); // Points to the same place in memory thus is true const copy = [1,2,3]; console.log(copy === newArr); // Doesn't point to the same place in memory and thus is false

Often when we transform data we want to keep our initial datastructure (e.g. Array) intact. We do this by making a exact copy of our array so this one can be transformed while the initial one stays intact.

Ways of copying an array:

const oldArr = [1,2,3]; // Uses the spread operator to spread out old values into the new array literal const newArr1 = [...oldArr]; // Slice with no arguments returns the newly copied Array const newArr2 = oldArr.slice(); // Map applies the callback to every element in the array and returns a new array const newArr3 = oldArr.map((el) => el); // Concat is used to merge arrays and returns a new array. Concat with no args copies an array const newArr4 = oldArr.concat(); // Object.assign can be used to transfer all the properties into a new array literal const newArr5 = Object.assign([], oldArr); // Creating via the Array constructor using the new keyword const newArr6 = new Array(...oldArr); // For loop function clone(base) { const newArray = []; for(let i= 0; i < base.length; i++) { newArray[i] = base[i]; } return newArray; } const newArr7 = clone(oldArr); console.log(newArr1, newArr2, newArr3, newArr4, newArr5, newArr6, newArr7);

Be careful when arrays or objects are nested!:

When arrays are nested the values are copied by reference. Here is an example of how this could lead to issues:

let arr1 = [1,2,[1,2,3]] let arr2 = [...arr1]; arr2[2][0] = 5; // we change arr2 console.log(arr1); // arr1 is also changed because the array inside arr1 was copied by reference

So don't use these methods when there are objects or arrays inside your array you want to copy. i.e. Use these methods on arrays of primitives only.

If you do want to deepclone a javascript array use JSON.parse in conjunction with JSON.stringify , like this:

let arr1 = [1,2,[1,2,3]] let arr2 = JSON.parse(JSON.stringify(arr1)) ; arr2[2][0] = 5; console.log(arr1); // now I'm not modified because I'm a deep clone

Performance of copying:

So which one do we choose for optimal performance. It turns out that the most verbose method, the for loop has the highest performance. Use the for loop for really CPU intensive copying (large/many arrays).

After that the .slice() method also has decent performance and is also less verbose and easier for the programmer to implement. I suggest to use .slice() for your everyday copying of arrays which aren't very CPU intensive. Also avoid using the JSON.parse(JSON.stringify(arr)) (lots of overhead) if no deep clone is required and performance is an issue.

Source performance test

Willem van der Veen's user avatar

Using jQuery deep copy could be made as following:

Oleksandr Tsurika's user avatar

You can also use ES6 spread operator to copy Array

ankur kushwaha's user avatar

Here are few more way to copy:

const array = [1,2,3,4]; const arrayCopy1 = Object.values(array); const arrayCopy2 = Object.assign([], array); const arrayCopy3 = array.map(i => i); const arrayCopy4 = Array.of(...array );

ganesh phirke's user avatar

Not the answer you're looking for? Browse other questions tagged javascript arrays deep-copy pass-by-value or ask your own question .

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Convert base-10 to base-0.1
  • Drawing a tree whose nodes are smaller trees
  • How to make a soundless world
  • 120V on fridge door handle when ground broken
  • Little spikes on mains AC
  • Arduino Uno Serial.write() how many bits are actually transmitted at once by UART and effect of baudrate on other interrupts
  • Rich Mental Images
  • Positivity for the mild solution of a heat equation on the torus
  • What would a planet need for rain drops to trigger explosions upon making contact with the ground?
  • Is it true that before European modernity, there were no "nations"?
  • Building rear track wheel from road wheel
  • Rocky Mountains Elevation Cutout
  • Does the science work for why my trolls explode?
  • 1950s comic book about bowling ball looking creatures that inhabit the underground of Earth
  • A word like "science/scientific" that can be used for ALL academic fields?
  • Python script to renumber slide ids inside a pptx presentation
  • How do I annotate a molecule on Chemfig?
  • Are these colored sets closed under multiplication?
  • Do I have to use a new background that's been republished under the 2024 rules?
  • What's the strongest material known to humanity that we could use to make Powered Armor Plates?
  • Fast leap year check
  • What is the action-cost of grabbing spell components?
  • I am an imaginary variance
  • Why does counterattacking lead to a more drawish and less dynamic position than defending?

javascript assignment copy

javascript assignment copy

Explore your training options in 10 minutes Get Started

  • Graduate Stories
  • Partner Spotlights
  • Bootcamp Prep
  • Bootcamp Admissions
  • University Bootcamps
  • Coding Tools
  • Software Engineering
  • Web Development
  • Data Science
  • Tech Guides
  • Tech Resources
  • Career Advice
  • Online Learning
  • Internships
  • Apprenticeships
  • Tech Salaries
  • Associate Degree
  • Bachelor's Degree
  • Master's Degree
  • University Admissions
  • Best Schools
  • Certifications
  • Bootcamp Financing
  • Higher Ed Financing
  • Scholarships
  • Financial Aid
  • Best Coding Bootcamps
  • Best Online Bootcamps
  • Best Web Design Bootcamps
  • Best Data Science Bootcamps
  • Best Technology Sales Bootcamps
  • Best Data Analytics Bootcamps
  • Best Cybersecurity Bootcamps
  • Best Digital Marketing Bootcamps
  • Los Angeles
  • San Francisco
  • Browse All Locations
  • Digital Marketing
  • Machine Learning
  • See All Subjects
  • Bootcamps 101
  • Full-Stack Development
  • Career Changes
  • View all Career Discussions
  • Mobile App Development
  • Cybersecurity
  • Product Management
  • UX/UI Design
  • What is a Coding Bootcamp?
  • Are Coding Bootcamps Worth It?
  • How to Choose a Coding Bootcamp
  • Best Online Coding Bootcamps and Courses
  • Best Free Bootcamps and Coding Training
  • Coding Bootcamp vs. Community College
  • Coding Bootcamp vs. Self-Learning
  • Bootcamps vs. Certifications: Compared
  • What Is a Coding Bootcamp Job Guarantee?
  • How to Pay for Coding Bootcamp
  • Ultimate Guide to Coding Bootcamp Loans
  • Best Coding Bootcamp Scholarships and Grants
  • Education Stipends for Coding Bootcamps
  • Get Your Coding Bootcamp Sponsored by Your Employer
  • GI Bill and Coding Bootcamps
  • Tech Intevriews
  • Our Enterprise Solution
  • Connect With Us
  • Publication
  • Reskill America
  • Partner With Us

Career Karma

  • Resource Center
  • Bachelor’s Degree
  • Master’s Degree

JavaScript Copy Array: A Guide

In JavaScript , copying an array is not as simple as using the assignment operator (=) to create a duplicate. If you’ve ever tried this, you will be surprised to find out that it only creates a link to the original list. What’s the deal?

In this guide, we’re going to talk about how to copy a JavaScript array. We’ll walk through the code for three JavaScript copy array strategies so you can get started copying arrays.

Find your bootcamp match

The problem with copying javascript arrays.

On some level, the “=” operator creates a copy of an array into a new variable . It’s more of a pointer than a copy though. This is because the “=” operator creates a reference to an original array. It does not create a duplicate of the existing array. 

Let’s try to create a copy of an array using the assignment operator with no other code:

Our code returns:

It looks like our array has been copied. “fruits” contains all the values from our “berries” array.

Now, let’s try to add an item to the “fruits” array:

We have added “Melon” to the fruits array. We then print out the values of “fruits” and “berries” to the console:

Both “fruits” and “berries” contain the same values. That’s because we have not technically cloned our array. We’ve just created a reference to it.

Any time we manipulate the “berries” array, the changes will be made in the “fruits” array.

How to Copy a JavaScript Array

The assignment operator does not copy an array. We’ve got to use another approach. Luckily for us, there are plenty of ways to create a copy of an array. The top three approaches are:

  • Using the spread operator
  • Using a for loop
  • Using Array.from

Let’s discuss these one-by-one.

Using the Spread Operator

The spread operator is a feature introduced in JavaScript ES6. It allows you to access the contents of an iterable object. This operator is often used to create a shallow copy of an array.

The spread operator consists of three dots, like an ellipsis (…). Let’s try to create a copy of our “berries” array from earlier:

We’ve used the spread operator to create a copy of our array. Let’s check the values of our arrays to make sure they are correct:

The value “Melon” was only added to the “fruits” array. This is because we used the spread operator to create a duplicate of the “berries” array. Now, the “fruits” array is its own array. Its values are separate from the “berries” array.

Using a for Loop

The tried and true method, using a for loop is a good way to create a copy of an array.

This method may not be as favored as the spread operator because it requires more lines of code. With that said, a for loop copies an object well.

We’ve declared two lists: berries and fruits. Fruits is initially an empty list. Then, we’ve used a for loop to loop through every item in the “berries” list. For each item in the list, the value is copied over to the “fruits” array.

Let’s run our test to see if our arrays are separate:

Success! “berries” and “fruits” are two separate arrays.

Using Array.from()

The Array.from() method turns any iterable object into an array. It goes through each item in an iterable and appends it to a new array. This means that it can be used to copy an array.

Let’s create a copy of our “berries” array again:

This solution, like the spread operator syntax, only takes up two lines of code. It’s an efficient and concise way of copying an array. Now, let’s run a test to check our new arrays:

Venus profile photo

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

Our arrays have been successfully copied.

Copying an array in JavaScript is easy when you know how.

The assignment operator isn’t enough to copy an array if you want to create a separate version of an array. This is because the assignment operator creates a pointer to an existing array; it does not create a new array.

You can create a copy of an array using the spread operator, a for loop, or the Array.from() method. Now you’re ready to copy arrays in JavaScript like an expert.

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication .

What's Next?

icon_10

Get matched with top bootcamps

Ask a question to our community, take our careers quiz.

James Gallagher

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Apply to top tech training programs in one click

IMAGES

  1. Array Of Strings To Uppercase In JavaScript

    javascript assignment copy

  2. Unique Characters In A String In JavaScript

    javascript assignment copy

  3. Series Of Operations In JavaScript

    javascript assignment copy

  4. Mastering JavaScript Assignment: A Comprehensive Guide

    javascript assignment copy

  5. String Slicing In JavaScript

    javascript assignment copy

  6. JavaScript Assignment Operators

    javascript assignment copy

VIDEO

  1. Java Script Logical Operator Lesson # 08

  2. DOM manipulation in JavaScript

  3. JavaScript Assignment Operators #basicsforbeginners #javascript #coding

  4. Week 3 Javascript Assignment

  5. How to copy text with the JavaScript Clipboard API

  6. JavaScript How to copy an existing element of the site?

COMMENTS

  1. Object.assign()

    Later sources' properties overwrite earlier ones. The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.

  2. How do I correctly clone a JavaScript object?

    I want to deep-copy a Javascript Object with all of its children and their children and so on. But since I'm not kind of a normal developer, ... That's an assignment, not a copy. clone.Title = "just a clone" means that obj.Title = "just a clone". - HoldOffHunger. Commented Aug 16, 2017 at 16:05

  3. 3 Ways to Copy Objects in JavaScript

    When you make a copy of a value stored in a variable, you create a new variable with the same value. For a primitive value, you just simply use a simple assignment: let counter = 1; let copiedCounter = counter; Code language: JavaScript (javascript) And when you change the value of the copied variable, the value of the original remains the same ...

  4. Object references and copying

    Object references and copying. One of the fundamental differences of objects versus primitives is that objects are stored and copied "by reference", whereas primitive values: strings, numbers, booleans, etc - are always copied "as a whole value". That's easy to understand if we look a bit under the hood of what happens when we copy ...

  5. JavaScript Object.assign() Method

    Description. The Object.assign() method copies properties from one or more source objects to a target object. Object.assign () copies properties from a source object to a target object. Object.create () creates an object from an existing object. Object.fromEntries () creates an object from a list of keys/values.

  6. How to copy objects in JavaScript: A complete guide

    JavaScript offers standard inbuilt object-copy operations for creating shallow copies: Array.from(), Array.prototype.concat(), Array.prototype.slice(), Object.assign(), and Object.create(), spread syntax. Here's an example of shallow copy in JavaScript: Here's an example of shallow copy in TypeScript.

  7. Using JavaScript Object.assign() Method in ES6

    The following shows the syntax of the Object.assign() method: The Object.assign() copies all enumerable and own properties from the source objects to the target object. It returns the target object. The Object.assign() invokes the getters on the source objects and setters on the target. It assigns properties only, not copying or defining new ...

  8. Object.assign() in JavaScript

    In JavaScript, the Object.assign() function copies properties from one or more source objects to a target object. It returns the target object. ... Object.assign() is commonly used to shallow copy objects, although the spread operator is generally faster than Object.assign() for shallow copying.

  9. Assignment (=)

    The assignment (=) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. ... JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

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

  11. The Best Way to Deep Copy an Object in JavaScript

    Copy an Object With Object.assign() Before ES6, Object.assign() was the most popular way to deep copy an object. Object.assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.

  12. Copying Objects in JavaScript

    let obj = {a: 1, b: 2,}; let copy = obj; obj. a = 5; console. log (copy. a); // Result // a = 5;. The obj variable is a container for the new object initialized. The copy variable is pointing to the same object and is a reference to that object. So basically this { a: 1, b: 2, } object is saying: There are now two ways to gain access to me. You have to pass through the obj variable or the copy ...

  13. What is shallow copy and deep copy in JavaScript

    This is known as a shallow copy. The newly created object has the same memory address as the old one. Hence, any change made to either of them changes the attributes for both. To overcome this problem, a deep copy is used. If one of them is removed from memory, the other one ceases to exist. In a way the two objects are interdependent.

  14. Javascript's assignment operation is to copy references?

    13. When primitives are assigned, they are assigned by value; references types (like your object) are assigned by reference (or, as Jon Skeet corrects me, they're assigned a copy of the reference). In your second example x and y both point to the same object in memory. That's why adding an abc property to one, also adds it to the other.

  15. JS Fundamentals: Object Assignment vs. Primitive Assignment

    Primitives vs. Objects. As a review, let's recall the different primitive types and objects in JavaScript. Primitive types: Boolean, Null, Undefined, Number, BigInt (you probably won't see this much), String, Symbol (you probably won't see this much) Object types: Object, Array, Date, Many others.

  16. Destructuring assignment

    It's called "destructuring assignment," because it "destructurizes" by copying items into variables. However, the array itself is not modified. It's just a shorter way to write: // let [firstName, surname] = arr; let firstName = arr [0]; let surname = arr [1]; Ignore elements using commas.

  17. javascript

    In Javascript, deep-copy techniques depend on the elements in an array. Let's start there. Three types of elements. Elements can be: literal values, literal structures, or prototypes. ... When we want to copy an array using the assignment operator ( =) it doesn't create a copy it merely copies the pointer/reference to the array. For example:

  18. JavaScript Copy Array: A Guide

    How to Copy a JavaScript Array. The assignment operator does not copy an array. We've got to use another approach. Luckily for us, there are plenty of ways to create a copy of an array. The top three approaches are: Using the spread operator; Using a for loop; Using Array.from; Let's discuss these one-by-one. Using the Spread Operator