Javascript – Clone an Array

Here is a simple way to copy an array, which contains primitive data types like string and integer, by value in Javascript.

var myArray = ['eureka', 30, true];
var clone = myArray.slice(0);

myArray[1] = 100;
console.log(myArray[1]); // output: 100
console.log(clone[1]);   // output: 30


But if myArray contains objects, those objects will be copied by reference. So if you really want to have a deep copy method, add the following clone function to Array.prototype.

Array.prototype.clone = function() {
  return this.slice(0);


Now you could make a copy by.

var myArray = ['eureka', 30, true];
var realClone = myArray.clone();


Doe =)

Reference: David Walsh – Clone Arrays with JavaScript


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.