user1649134 user1649134 - 9 months ago 23
Javascript Question

How to access variable in Javascript?

var a=[1,2,3];
var b=a;
b.push(4,5);
console.log(b);
console.log(a);


I want a value as [1,2,3]. But it printing [1,2,3,4,5] How can I achieve this. Please help. Thanks in advance

Answer Source

You are assigning the array's object reference to another one variable. But here what you want to do is to copy the array to create a new instance.

 var a=[1,2,3];
 var b= a.slice(0);
 b.push(4,5);

 console.log(b); //[1,2,3,4,5]
 console.log(a); //[1,2,3]

Array.prototype.slice will create a copy of the original array when the start value passed along is 0. But if you are really concerned about passing a hard coded value, use the call's variant.

var b= [].slice.call(a);