I was playing around with reverse() to see how it works and came across this interaction that I can’t understand at all. Here is the initial code:
let muhArray = [1,2,3,4,5];
let reversedArray = muhArray.reverse();
console.log(`muhArray: ${muhArray}`);
console.log(`reversedArray: ${reversedArray}`);
This returns:
muhArray: 5,4,3,2,1 (Original array changed as well)
reversedArray: 5,4,3,2,1
I figured that since reverse() reverses arrays in-place, even if it is an initilization, it changes the original muhArray anyways. So I created a copy(muhArrayCopy) to preserve the original array.
let muhArray = [1,2,3,4,5];
let muhArrayCopy = muhArray;
console.log(`muhArrayCopy: ${muhArrayCopy}`);
let reversedArray = muhArray.reverse();
console.log(`reversedArray: ${reversedArray}`);
This returns:
muhArrayCopy: 1,2,3,4,5
reversedArray: 5,4,3,2,1
Up until this point everything seems fine, but changing the order made me realise muhArray.reverse() affects already declared and initialized muhArrayCopy as well.
let muhArray = [1,2,3,4,5];
let muhArrayCopy = muhArray;
let reversedArray = muhArray.reverse();
console.log(`muhArrayCopy: ${muhArrayCopy}`);
console.log(`reversedArray: ${reversedArray}`);
Such order returns:
muhArrayCopy: 5,4,3,2,1
reversedArray: 5,4,3,2,1
Is this maybe a code execution order thing? I have read about hoisting but that does not seem to explain it, as far as I can understand. I am all new to programming so I have little to no knowledge about it.
Thanks in advance.
>Solution :
js is call by reference, so
let muhArrayCopy = muhArray;
does not create a copy, it puts the reference of variable in the other one, so both are affected when something happens to the other.
let muhArray = [1,2,3,4,5];
let muhArrayCopy = [...muhArray];
let reversedArray = muhArray.reverse();
console.log(`muhArrayCopy: ${muhArrayCopy}`);
console.log(`reversedArray: ${reversedArray}`);
this should solve it. here [...muhArray] we are creating a copy of the array.