About a copy of array in Vanila Javascript

As you may know, we can’t make a copy of array in Vanila JS with the code below. (Not a library based js. That is Vanila JS.)

var drinks = ["cola","orange juice", "tea", "beer"];

var copyOfDrinks = drinks;

drinks.push("milk");

console.log(copyOfDrinks);

We see “copyOfDrinks” show the contents of “drinks” because the variable is a reference of the original array. Simple “for loop” will do the job in this case.

var drinks = ["milk","whisky"];

var copyOfDrinks = [];

for(let i = 0; i < drinks.length; i++){

copyOfDrinks[i] = drinks[i]

}

drinks.push("lemon juice");

console.log(copyOfDrinks);


In modern JS (ES6,7), they created a syntax for doing this.


var copy = [...drinks];

Reference:
Spread_syntax

Comments

Leave a Reply

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