JavaScript Copy Array: How to make an exact copy of an array in JavaScript

preview_player
Показать описание
In this tutorial, you’ll learn how the JavaScript copy array process works.

Don’t forget to subscribe to the Junior Developer Central channel for more videos and tutorials!

You’ll learn about two ways that JavaScript can be used to copy an array. First, we’ll take a look at the slice function which is a built-in JavaScript function that can be called on an array.

The slice function actually returns back a portion of an array based on the value you supply it as an argument. Typically you would use this to miss the first character from a string (like when using JavaScript to capitalize the first letter of a string). However, in this example, you’ll see that not provided the slice function with a value just returns a complete copy of the entire array and there you have a copy of your original array.

The second method you’ll learn about is the ES6 spread operator which is usually used to insert the values of an entire array into another one. You’ll see in the video that inserting the values into a blank array allows you to create an exact copy.

So JavaScript variables that aren’t primitive data types are copied by reference when you just assign variableA to variableB. It therefore makes sense that a JavaScript array is copied by reference too. In the final section of the video, you’ll see why you can’t just copy a JavaScript array by assigning the variable name to another variable.

Other videos in the JavaScript Snippets series:

Рекомендации по теме
Комментарии
Автор

A huge like! Also we can use var copyOfArray = Array.from(array)

liyan
Автор

how to make the copy of new array immutable ? everytime i change something in array1, the array2 also changes.

sahil-singh