Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some operations not alter an array that was passed to a function?

Scenario 1:

var myArray = [2, 3, 4, 5];
function doStuff(arr) {
  arr = [];
}
doStuff(myArray);
console.log(myArray); // [2,3,4,5]

Scenario 2:

var myArray = [2, 3, 4, 5];
function doStuff(arr) {
  arr.pop();
}
doStuff(myArray);
console.log(myArray); // [2,3,4]

Why does scenario 1 not update the globally declared array but scenario 2 does?

like image 479
grabury Avatar asked Feb 12 '26 21:02

grabury


1 Answers

In the first example:

You are altering the variable arr which is merely just holding a reference to the array [2, 3, 4, 5], so instead of holding a reference to [2, 3, 4, 5], it will hold a reference to another array [].

At the line var myArray = [2, 3, 4, 5];:

myArray -----------------------------------> [2, 3, 4, 5]

Then at the line doStuff(myArray);:

myArray -----------------------------------> [2, 3, 4, 5]
                                                  ↑
arr ----------------------------------------------/

Then at the line arr = [];:

myArray -----------------------------------> [2, 3, 4, 5]

arr ---------------------------------------> []

=> So, after the call to doStuff, myArray is still [2, 3, 4, 5].

In the second example:

You are using the reference to [2, 3, 4, 5] stored in arr to call a function pop on it that alters it.

At the line var myArray = [2, 3, 4, 5];:

myArray -----------------------------------> [2, 3, 4, 5]

Then at the line doStuff(myArray);:

myArray -----------------------------------> [2, 3, 4, 5]
                                                  ↑
arr ----------------------------------------------/

Then at the line arr.pop();:

myArray -----------------------------------> [2, 3, 4, 5].pop()
                                                  ↑
arr.pop() ----------------------------------------/

Which alters the array to:

myArray -----------------------------------> [2, 3, 4]
                                                  ↑
arr ----------------------------------------------/

=> So, after the call to doStuff, myArray is now [2, 3, 4].

like image 67
ibrahim mahrir Avatar answered Feb 14 '26 11:02

ibrahim mahrir