Two easy ways to copy or clone an Array in Javascript

- With slice method:

This method returns the selected elements in an array, as a new array object

Syntax and example:

// array.slice(start, end)
const source = ['x', 'y', 'z', 0, 1, 2]  
const copied = source.slice()


- Use concat method:

Syntax and example:

//array1.concat(array2, array3, ..., arrayN)
const source = ['x', 'y', 'z', 0, 1, 2]  
const copied = [].concat(source)


Like the slice method, concat method will return new array.

clone arrayconcatcopy arrayjavascriptslice

© 2019 4codev

Created with love by Sil.