Clone array in Javascript

How to clone array in javascript? how to duplicate an array in javascript? that’s usual question we come across then people start saying use loops and copy one array to other. because if you directly assign one array to other variable it’s actually assigned via reference. so either way you change it’s reflected in both variables ! How to clone or duplicate array in simple steps let’s find it out!

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


Now how to use it? simple!

Assume you have an array called as myOriginalArray. let’s duplicate it into other array with name myDuplicateArray. We will do it like below

var myDuplicateArray = myOriginalArray.clone();

What did just happen?!

We basically extended functionality of Array provided by javascript! prototype enables us to extend functionality of existing classes. Don’t forget to write prototype code before you use it!!!! Thus we have successfully created duplicate of an original array in javascript!


Add a Comment

Your email address will not be published. Required fields are marked *