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
CodePudding user response:
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.