Search code examples
javascriptarrayssplice

Why splice() method changes the value of other array?


I have an array say

var list = ["first", "second"];

now I assign list to some other variable say

var temp = list;

Now when I use splice on list like

list.splice(0,1);

Now when I check the value of list it shows

list = ["second"]

Also when I check the value of temp then it says

temp = ["second"]

I want to know why is that so? Why the value of temp is changed?


Solution

  • when you do an assignment like var temp = list you're creating a reference temp to list. So since splice changes list array in-place, you're also changing temp

    Use slice instead which returns a copy of the array, like so

    var temp = list.slice();