Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutate JavaScript Array Inside Function

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?

like image 931
inperspective Avatar asked Mar 28 '26 21:03

inperspective


1 Answers

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.

like image 100
Felix Kling Avatar answered Apr 01 '26 06:04

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!