JS Bites: Copy An Array Using the Spread Operator

Quick tutorial on how to copy an array in JS using the spread operator.

let source_array = [1, 2, 3];
let copy_array = [...source_array];
source_array.push(4);

console.log("source_array says: ", source_array);
console.log("copy_array says: ", copy_array);

// console output
"source_array says: " [1, 2, 3]
"copy_array says: " [1, 2, 3, 4]

What’s going on here? The spread operator does what it sounds like. It takes each element from the source and spreads those elements out into another array. Similar to taking a handful of seeds which can be thought of as a single object, when compressed in the hand, however, when the hand opens to sling those seeds out to be planted, they spread out into their individual elements.

That’s how my brain thinks about this anyway. Alternatively, we could have written the code this way with the same results.

let source_array = [1, 2, 3];
let copy_array = [...source_array, 4];

console.log("source_array says: ", source_array);
console.log("copy_array says: ", copy_array);

Here what we’re doing is adding the extra element to the copy_array as we are using the spread operator. When I first learned about this, an example written this way helped me understand it better.

And I read that code in my head like this: “Spread these other things out into this new array and then add this one right here.”

Hope you found this useful!

Did you enjoy this article?
Signup today and receive free updates straight in your inbox. We will never share or sell your email address.
I agree to have my personal information transfered to MailChimp ( more information )
Powered by Optin Forms