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

Modifying an array also changes the array it is inherited from

While working on one of my project I encountered the following problem. following is the best representation of the problem I faced.

function get(){
    return [0,0];
}

let arr:number[] = get();//arr=[0,0]
let arr2:number[] = arr;//arr2=[0,0]
arr2[1]=arr2[1]+1;//arr2=[0,1] arr[0,0]

console.log(arr)//outputs [0,1]

the program outputs [0,1] even though I never touched the variable arr.
I think it is a bug or if not I would be grateful to know the underlying reasoning behind this output.
Thanks in Advance

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

>Solution :

In Javascript Objects (which Arrays basically are) are passed by reference (so if you say arr2 = arr both arr and arr2 are pointing to the same space in memory.

That is intended behaviour (and not a bug)

JS Primitives (strings, integers, booleans) are passed by value (which would produce the behaviour you are looking for)

If you want to learn more you can search for "Pass by reference vs value Javascript" (there are tons of resources out there that explain this in great detail)

Edit: To pass arrays by value, you need to make a copy. This could look something like arr2 = [...arr] (this is only a shallow copy) – but you really need to understand the difference between passing by value and reference.

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