0

Why is my input parameter inArr being modified when I update local variable arr in the JavaScript code below?

function test(inArr) {
    var arr = inArr;

    for (let i = 0; i < 3; i++) {
        arr.push(i);
        console.log( "arr = ", arr, "inArr = ", inArr );
    }
}

test([]);

This outputs:

arr =  [ 0 ] inArr =  [ 0 ]
arr =  [ 0, 1 ] inArr =  [ 0, 1 ]
arr =  [ 0, 1, 2 ] inArr =  [ 0, 1, 2 ]
HeatfanJohn
  • 7,143
  • 2
  • 35
  • 41
  • See https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language –  Feb 11 '20 at 20:15
  • 1
    Duplicate of: [Copy array by value](https://stackoverflow.com/questions/7486085/copy-array-by-value) – Dexygen Feb 11 '20 at 20:15
  • 1
    Arrays are objects in Javascript and objects are always passed by reference in JavaScript, also in PHP for example. – Daniel W. Feb 11 '20 at 20:15
  • Sorry all for the duplicate question, but sometimes you need to know the answer to the question in order to search for the answer ... thanks gain ... – HeatfanJohn Feb 11 '20 at 20:20
  • @HeatfanJohn Yeah, sometimes the challenge is in knowing just *what* to search for. No apology is necessary. We've all been there. –  Feb 11 '20 at 20:26

2 Answers2

1

because they are the same.

function test(inArr) {
    var arr = [].concat(inArr);

    for (let i = 0; i < 3; i++) {
        arr.push(i);
        console.log( "arr = ", arr, "inArr = ", inArr );
    }
}

test([]);
Mauricio
  • 84
  • 1
  • 8
1

JavaScript arrays are assigned by reference, so when you make your assignment, both variables are pointing to the same array in memory. Any change to one will also change the other.

You can create a new array with those values using the spread operator:

var arr = [...inArray];
Ed Lucas
  • 5,955
  • 4
  • 30
  • 42
  • How can you post an answer on a closed question. I can't do that and i have 22k more rep :-S – Daniel W. Feb 11 '20 at 20:20
  • Most likely I added the answer just before it was closed. – Ed Lucas Feb 11 '20 at 20:25
  • No, you added it afterwards (3-4 minutes later). I see, there is a serverside grace period which allows posting even if the question got closed. https://meta.stackexchange.com/questions/91922/how-was-this-answer-posted-after-this-question-was-closed – Daniel W. Feb 11 '20 at 20:26
  • That makes sense. I answered it from my phone, which doesn't have the same client-side restriction. – Ed Lucas Feb 11 '20 at 20:29