2

Since arrays are passed to functions by reference, when I set the array to be equal to something else inside a function, and try to log it outside of the function again, why does the value remain the same even though I modified it in the function?

let arr = [1, 2];
console.log(arr); // Logs [1, 2]
add(arr, 3)
console.log(arr); // Logs [1, 2] again

function add(array, el)
{
    array = [el];
    console.log(array); // Logs [3]
}

Why does the console.log after calling add log out [1, 2] instead of [3] (which is the value of the el parameter)?

DwayneCena
  • 23
  • 2
  • 2
    Because the assignment to `array` inside the function is an assignment to the *local variable*, not the relatively global `array`. – Pointy Aug 21 '19 at 15:16

2 Answers2

4

You aren't modifying the array.

You're changing the value of the array variable (from a reference to the old array to a reference to a new array).

For comparison, if you were to modify the existing array:

let arr = [1, 2];
console.log(arr);
add(arr, 3)
console.log(arr);

function add(array, el) {
  array.length = 0;
  array.push(el);
  console.log(array);
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You're confusing the scope of the array.

When you pass in an array to the function and set that variable equal to something else like so;

function add(array, el)
{
  array = [el];
}

You're just setting the variable equal to something else and you're not modifying the array. If you want to modify the array you would do something like:

 function add(array, el)
 {
    array[0]=el; // changing the first element to 3
 }

Now you will see the array is updated with the first element to 3. This is how it works with updating the array.

If you want the array to be an entirely new array you would do something like:

arr = add(arr, 3);

function add(array, el)
{
  array = [el];
  return array;
}