How do I copy an array in JavaScript?

To copy or clone an array in JavaScript, you can use the array.slice(), array.concat(), array.from() methods, and the spread operator ("..."). The slice() method is the simplest and fastest way to copy the contents of an existing array (the original array remains unchanged) into a new array without any parameters. The concat() method is intended to merge two arrays into one, but you can also use it to clone an array by calling it method on an empty array and passing the original array as a function parameter. The concat() method creates a new copy of the array like slice() method. The from() method is another way to clone an array; it creates a new shallow-copied array (the method only goes down one level when cloning an array). You can also use the spread operator ("...") to clone an array by "expanding" its elements. The spread operator creates a shallow copy of the original array. If you are working with a multi-dimensional array or an array containing objects, you will need to look for other alternatives. In this JavaScript copy array example, we use the spread operator ("..."). Below you can see more examples of copying JavaScript arrays with a detailed description of each method. Click Execute to run the JavaScript Copy Array Example online and see the result.
Loading...