1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i got it but currently is there is a way i can rewrite my program so that arr does not change??\
@YeshwinVermaTheProgrammer see my edit (but please make yourself familiar with passing by reference vs value) - it is a fudamental part of JS (and not understanding it will lead to big big problems)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.