Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript confusing order of execution

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading