3

In JavaScript, how do I mutate the value of an array inside of a function? I know that happens when using certain array methods, but it doesn't seem to work for normal assignment.

var arr = [4]

function changeArray(arr) {
arr = [1,2,3];
}

// arr is still equal to [4]. I want it to equal [1,2,3].

It's my understanding that this code doesn't change the value of "arr" outside of the function. How can I do it in a way that mutates the array that was passed as an argument?

1 Answer 1

7

You can use .splice:

arr.splice(0, arr.length, 1, 2, 3);

Or you can empty the array and .push the values:

arr.length = 0;
arr.push(1, 2, 3);
// or given an array of values
arr.push.apply(arr, newValues);

However, make sure it is clear that the function changes the array in place. While there are native functions that does this (like Array#sort), I'd argue that this is not as common as simply returning a new array.


It's my understanding that this code doesn't change the value of "arr" outside of the function.

Correct. Assigning a new value to a variable or property never changes the value of another variable or property (exceptions: global scope and with statements). You basically tried to change the value of a variable, not mutate the value itself.

JavaScript is call/pass/assign by value (Wikipedia also mentions "by sharing"), not by reference.

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

2 Comments

The concat method does not mutate the original array. Therefore, if you want to mutate an array by adding another array inside a function, you need to use a combination of a loop and push/splice?
If you simply want to add multiple elements from an array, you can use .push + .apply: arr.push.apply(arr, newElements);

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.