Search code examples
javascriptarrayssplice

.splice() - how to protect oryginal array?


var a = [1, 2, 3];
var b = a;      // b = [1, 2, 3];

console.log(a); // 1, 2, 3
console.log(b); // 1, 2, 3

b.splice(0, 1);
console.log(b); // 2, 3
console.log(a); // 2, 3 <----------- WHY?

I just needed to copy my oryginal "a" array because I want to stay it as [1, 2, 3] forever. How to pop first element from "b" array without touching the oryginal one? Thanks


Solution

  • Your code just needs one small fix:

    var a = [1, 2, 3];
    var b = a.slice();
    

    I'm not sure of the specifics, but when you are assigning arrays or objects to another variable, the array/object is not copied by value, but rather by reference. .slice method duplicates all elements in the array to the new element rather than just saving a reference to the old one.