How to Copy an Array by Value in JavaScript?

How to Copy an Array by Value in JavaScript?

When working with arrays in JavaScript, you may find a need to create a copy of an array without modifying the original array. However, suppose you are directly trying to assign an array to a new variable. In that case, it only creates a reference to the original array, which means making changes in one affects the other. So, how do you copy an array by value in JavaScript? In this blog, you will explore various methods to copy an array, including the difference between shallow and deep copies in JavaScript.

Table of Contents:

How to Make a Shallow Copy of an Array in JavaScript

A shallow copy creates a new array but holds a reference to the objects inside it. In other words, if the array contains primitive values like numbers or strings, then they are fully copied. But if the array contains nested objects or other arrays, then only references are shared, not fully copied. Here are some methods to perform a shallow copy in JavaScript:

Method 1: Copy Array in JavaScript Using Spread Operator

The spread operator in JavaScript is a simple and modern way to copy an array by value. It is denoted using { … }. It is an excellent way to quickly clone array in JavaScript.

Syntax:

const newArr = […arr];

Example:

Javascript

Output:

Using the Spread Operator

Explanation: In this example, you’re using the spread operator in JavaScript program for copying the value of an array into a new variable. After copying all the values from the original to the copied array. You can check both references by using the === operator.

Method 2: Clone an Array in JavaScript with Array.from()

The Array.from() creates a new array from an existing one, and it is more useful when you are working with array-like objects. This method provides another reliable way to clone array in JavaScript.

Syntax:

const newArr = Array.from(arr);

Example:

Javascript

Output:

Using an Array.from() Method

Explanation: In this example, you’re using the Array.from() method to copy an original array into a copied array.

Method 3: Use slice() to Shallow Copy an Array in JavaScript

The slice() method is used to shallow copy an array in JavaScript. In other words, when the slice() method is used to copy an array by value in JavaScript, it creates a completely new array with a different reference. However, for nested objects or arrays, only their references are copied. This is a key aspect of how the JavaScript slice array method works for shallow copies. It’s a common method to clone array in JavaScript for top-level elements.

Syntax:

const newArr = arr.slice();

Example:

Javascript

Output:

Using slice() Method

Explanation: Use the .slice() method to create a copy of the original array with a completely different reference.

Method 4: Duplicate Array Elements Using map() in JavaScript

The map method helps you to copy an array by value in JavaScript. It also allows you to perform some extra modifications in the newly copied array. This method can also be used to clone array in JavaScript while transforming its elements. You can use the JavaScript map method to iterate over elements and return a new array.

Syntax:

const newArr = arr.map(item => item);

Example:

Javascript

Output:

Using the map() Method

Explanation: The JavaScript map method is another simple method to copy array elements from the original array.

How to Make a Deep Copy of an Array in JavaScript

A deep copy creates a complete copy of an array so that the copied array is independent of the original array. Here are some methods to create a deep copy of an array in JavaScript:

Method 1: Deep Clone Array in JavaScript Using JSON.stringify() and JSON.parse()

This method converts an array to a JSON string and then back to an array. In this way, it ensures a full deep copy of an array by value in JavaScript. This is a common technique to fully clone array in JavaScript when dealing with nested objects, though it has limitations.

Syntax:

const newArr = JSON.parse(JSON.stringify(arr));

Example:

Javascript

Output:

Using JSON.stringify() and JSON.parse()

Explanation: The JSON.stringify() and JSON.parse() combine to create a complete, independent copy of the original array.

Method 2: Deep Copy Array Using structuredClone() in JavaScript

structuredClone() provides a built-in deep copy of an array by value in JavaScript. The only disadvantage of using this is that it is not supported in all environments (older browsers and Node.js versions before 17). It’s the most straightforward way to clone array in JavaScript deeply when available.

Example:

Javascript

Output:

Using structuredClone() Method

Explanation: structuredClone() is used to create a deep copy of an array in JavaScript, but it cannot work in all environments. Thus, it is not recommended for use.

Performance Comparison of JavaScript Array Copy Methods

If you’re copying values from the original array into another variable, then choose the method wisely based on the specific needs and your browser support.

  • The spread operator { … } and slice() are the fastest methods to copy simple arrays. When considering performance for copying arrays, the JavaScript slice array method is often a popular choice for shallow copies.
  • Use JSON.stringify() and JSON.parse(), besides using structuredClone() for performing a deep copy of an array by value in JavaScript. The JavaScript map method can also be used for performance-sensitive shallow copies or transformations.

Difference Between Shallow and Deep Copy in JavaScript

Aspect Shallow Copy Deep Copy
Definition Copies only the top-level properties Copies all levels of nested objects
Nested Objects Still reference the same memory (shared) Completely new copies are created
Mutation Impact Changes to nested objects affect the original Changes do not affect the original
Performance Faster and less memory-intensive Slower, and more memory usage
Methods to Create Object.assign(), spread operator ({…obj}) structuredClone(), JSON.parse(JSON.stringify(obj))
Use Case When nested data does not need to be independent When full data isolation is required
Example let copy = {…original} let copy = JSON.parse(JSON.stringify(original))
Limitations Not safe for deeply nested or complex structures Can handle deep and complex objects (with the proper method)

Common Mistakes to Avoid When Copying Arrays in JavaScript

Here are the common mistakes when copying arrays in JavaScript:

1. Using = to Copy an Array: Developers often use the assignment operator (=) thinking it creates a new array, but it only creates a reference to the original array.

Example:

Javascript

Output:

Using = to Copy an Array

Explanation: This code assigns the original to the copy by reference, so both variables point to the same array. When copy.push(4) is called, it also modifies the original array.

2. Assuming Spread Operator or slice() Creates a Deep Copy: The spread operator ([…]) or JavaScript slice array method only creates a shallow copy, which means nested objects or arrays still reference the same memory.

Example:

Javascript

Output:

Assuming Spread Operator or slice()

Explanation: This code creates a shallow copy using the spread operator in JavaScript, so nested arrays are still shared. Thus, changing the copy[0][0] also changes the original[0][0].

3. Using JSON.stringify() and JSON.parse() Without Understanding the Limitations: While this method is used for deep copying, it fails when the array contains functions, undefined data, Date, or circular references.

Example:

Javascript

Output:

Using JSON.stringify() and JSON.parse() Without Understanding the Limitations

Explanation: This code uses JSON.parse(JSON.stringify(…)) to deep copy the array, but it loses undefined, functions, and converts Date to a string, resulting in data loss or change.

4. Trying to Copy Arrays with Circular References Using JSON: JSON methods cannot handle circular references and will throw an error when attempted.

Example:

Javascript

Output:

 Trying to Copy Arrays with Circular References Using JSON

Explanation: This code creates a circular reference by pushing the array into itself, and JSON.stringify() fails because it cannot handle circular structures, resulting in a TypeError.

5. Unnecessarily Deep Copying Simple Arrays: Using heavy methods like structuredClone() or JSON for simple arrays adds unnecessary overhead and can slow down performance.

Example:

Javascript

Output:

5. Unnecessarily Deep Copying Simple Arrays

Explanation: This code uses structuredClone() to deep copy a flat array, which works correctly, but it’s unnecessary overhead for simple, non-nested arrays.

Use Cases for Copying Arrays in JavaScript

  • Preserving Original Data: Copying an array lets you make changes without modifying the original, which is useful in undo/redo functionality.
  • Working with Immutable Data Structures: In frameworks like React, copying arrays helps follow immutability principles when updating state.
  • Filtering or Transforming Data: When applying .filter(), .map(), or .sort(), it’s often safer to copy the array first to avoid unwanted mutations.
  • Cloning Data Before API Requests: Copying arrays before sending or modifying them ensures the original data remains intact for future use.
  • Resetting or Reusing Arrays: You can save an original version of an array and use the copy to manipulate or reset it later.
  • Avoiding Side Effects in Functions: Copying arrays inside functions prevents unexpected side effects when arrays are passed by reference.
  • Managing Form or UI State: In UI development, copying arrays allows controlled updates to list-based components like checkboxes, dropdowns, or dynamic inputs.
  • Testing and Debugging: Creating copies lets developers safely test logic without altering the source data during debugging.

Conclusion

Creating an independent or deep copy of an array by value in JavaScript is important because it helps you to work separately on two independent arrays containing the same value. You have spread operator {…}, Array.from(), slice(), and map() methods used to shallow copy an array in JavaScript, and also you have JSON.stringify() and JSON.parse() for creating deep copies. Choosing the right method based on your needs helps you to create copies efficiently.

 

The following articles offer a thorough overview of HTML fundamentals and important concepts.-

Bootstrap Interview Questions – Walk through Bootstrap interview questions and their implementation in this blog.

What Does Enctypemultipart Form Data Mean In An HTML Form – Find clear explanations of enctype=”multipart/form-data” in HTML forms in this blog.

How To Vertically Align Text Next To An Image Using CSS – This blog teaches how to align text vertically next to an image using CSS.

Regex To Match Open HTML Tags Except Self Contained XHTML Tags – Learn to construct regex that matches open HTML tags while ignoring self-contained ones in this blog.

Why Margin Top Does Not Work In CSS – This blog identifies common causes of margin-top not working in CSS.

CSS Margin Auto To Horizontally Center Element – Discover how to apply margin: auto for horizontal centering in CSS in this blog.

CSS Display Table Method To Center The Element Horizontally – Check how the display: table method helps center content horizontally in CSS through this blog.

Using Onclick In HTML A Bad Practice – This blog explains the downsides of using onclick directly in your HTML code.

Parsing HTML and XML with Regular Expressions – Explore regular expression techniques for parsing HTML and XML in this blog.

HTML Links – This blog provides an overview of how to create effective HTML links.

How to Copy an Array by Value in JavaScript – FAQs

Q1. How to deep copy an array in JavaScript?

Use structuredClone(array) to deep copy an array in JavaScript.

Q2. How to copy array in JavaScript without reference?

Use the spread operator in JavaScript like […array] to copy an array without referencing the original.

Q3. Can I deep copy an array in JavaScript with functions or dates?

Yes, use structuredClone() to deep copy an array in JavaScript with functions or dates—but note: it does not support functions.

Q4. How to declare an array in JavaScript?

In JavaScript, you can declare an array using let, var, and const. Syntax: const arr = [10,20,30]

Q5. What is the difference between shallow and deep copy?

A shallow copy creates a new array but contains references to the nested objects, which means making changes in the nested objects can make changes in the original one. While A deep copy creates a completely independent copy, including all nested objects.

Q6. Is structuredClone supported in all browsers?

No, structuredClone is not supported in all browsers; it’s available in most modern ones but not in older versions.

Q7. Is slice faster than spread for large arrays?

Yes, slice() is generally faster than the spread operator in JavaScript for large arrays.

Q8. How to clone nested arrays without JSON?

Use structuredClone(nestedArray) to clone nested arrays without using JSON.

Q9. What is the JavaScript map method?

The JavaScript map method creates a new array by applying a function to each element of the original array.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner