xngtng
xngtng

Reputation: 160

JavaScript - Array passed by reference but lost when reassigned

In the following JS code, why doesn't f3(arr2) change the value of arr2 like f2(arr1) did to arr1? Is there any way to make f3 work as expected (if possible, without returning the modified array)?

var arr1 = [1, 2, 3, 4];
var arr2 = [1, 2, 3, 4];

function f1() {
    return [2, 3, 4, 5];
}

function f2(arr) {
    arr.push(5);
}

function f3(arr) {
    arr = f1();
}

f2(arr1);
console.log(arr1); // [ 1, 2, 3, 4, 5 ]

f3(arr2);
console.log(arr2); // [ 1, 2, 3, 4 ], expect [2, 3, 4, 5]

Upvotes: 5

Views: 737

Answers (4)

Bekim Bacaj
Bekim Bacaj

Reputation: 5955

quote: "console.log(arr2); // [ 1, 2, 3, 4 ], expect [2, 3, 4, 5]"

The reason that you are not getting what you are expecting is this part here

function f3(*arr*) { *arr* = f1(); }

You are assigning the array [2,3,4,5] to the argument-name arr of the function f3, not to the arr2. Arr2 remains of course untouched and in its original state throughout your script.

function f3(*arr*) { *arr2* = f1(); } will do it.

But this answer is not my final. This is only how it appears.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386654

You could do it in a single step:

Array.prototype.splice.apply(arr, [0, arr.length].concat(f1()));

var arr1 = [1, 2, 3, 4];
var arr2 = [1, 2, 3, 4];

function f1() {
    return [2, 3, 4, 5];
}

function f2(arr) {
    arr.push(5);
}

function f3(arr) {
    Array.prototype.splice.apply(arr, [0, arr.length].concat(f1()));
}

f2(arr1);
document.write('<pre>' + JSON.stringify(arr1, 0, 4) + '</pre>');

f3(arr2);
document.write('<pre>' + JSON.stringify(arr2, 0, 4) + '</pre>');

Upvotes: 1

Quốc Hồ Thanh
Quốc Hồ Thanh

Reputation: 35

When you pass anything (Whether that be an object or a primitive), all javascript does is assign a new variable while inside the function... just like using the equal sign (=)

How that parameter behaves inside the function is exactly the same as it would behave if you just assigned a new variable using the equal sign.. Take these simple examples. You can ref: Link

Upvotes: -1

Quentin
Quentin

Reputation: 943605

If you want to modify the array, then you actually have to modify the array. You can't just write a reference to a different array over the variable (as that just throws away the local reference to that array).

function f3(arr) {
    arr.length = 0; // Empty the array
    f1().forEach(function (currentValue) { arr.push(currentValue); });
}

Upvotes: 3

Related Questions