Manipulating Copy of an Array in Java Script without Affecting its Original
An array in JavaScript is also an object and objects are always passed/assigned by reference.
I have an array of alphabets where
alpahabets = ["a", "b", "c", "d"];
and have its copy in
copyofalphabets = alphabets;
Now if i print alphabets and copyofalphabets i have
alpahabets => [“a”, “b”, “c”, “d”]
copyofalphabets => [“a”, “b”, “c”, “d”]
So if i change
copyofalphabets[0]="e";
and then I print values of both , i have
alpahabets => [“e”, “b”, “c”, “d”]
copyofalphabets =>[“e”, “b”, “c”, “d”]
This is because both variables have a reference to the same object.
To make an independent copy of an array rather than a copy of the refence to it, you can use the array slice method.
copyofalphabets = alpahabets.slice(0);
Now if i print both arrays I have
alpahabets => [“e”, “b”, “c”, “d”]
copyofalphabets =>[“e”, “b”, “c”, “d”]
Now even if you change any index value in copyofalphabets, the original array of alphabets are not affected. It will remain the same.
copyofalphabets[0]="a";
Now printing both arrays will result in
alpahabets => [“e”, “b”, “c”, “d”]
copyofalphabets =>[“a”, “b”, “c”, “d”]

Post a Comment