I was solving a probelm using javascript when i found out this strange behaviour of javascript when using and when not using slice() mthod. I don’t know if this behaviour is strange only to me or what, i googled it but couldn’t help myself to clear confusion.
Here is an example to illustrate strage behaviour, atleast according to me (i guess):
const arr1 = [1, 2, 3];
const arr2 = arr1;
console.log(arr2);
arr2.splice(1, 0, 1);
console.log(arr2);
console.log(arr1);
According to this the output is :
[ 1, 2, 3 ]
[ 1, 1, 2, 3 ]
[ 1, 1, 2, 3 ]
The value of variable arr1 also changes althoughi didnt assign any changes to this variable. I guess it is some sort my mutating from new variable or what i don’t know.
But when is use slice() method to copy value to another variable:
The code be like this
const arr1 = [1, 2, 3];
const arr2 = arr1.slice();
console.log(arr2);
arr2.splice(1, 0, 1);
console.log(arr2);
console.log(arr1);
The output comes like this
[ 1, 2, 3 ]
[ 1, 1, 2, 3 ]
[ 1, 2, 3 ]
Now the value doesn’t change which was required to solve my problem.
Why this happens when not using slice and what does slice do to prevent it?
Please help me.