OneBite.Dev - Coding blog in a bite size

copy an array in Javascript

Code snippet on how to copy an array in Javascript

let array1 = [1,2,3];
let array2 = [...array1];

This code will copy elements from an array, named array1, and store them into another array, named array2. The spread operator (…) allows to spread out the elements from array1 and store them into a new array2. The original array array1 will not be modified, thus the copy operation. In other words, array2 will be a replica of array1.

javascript