Is it possible in Javascript to pass an array (from outer scope) to a function, and mutate the original array?
I've read several answers mentioning that f()
's arr
argument is actually a copy, it's name just shadows the outer scope variable. Other mention arrays are always passed by reference, but are 'copied' (that is a confusing explanation).
But if that is the case, why does arr[0] = 'a';
find the arr
reference in outer scope? But arr = ['a', 'b']
does not?
If arr = ['a', 'b']
was declared in the function with a blockscoped var type (let
, const
), that would make more sense..
let a = [0,0,1,1,1,2,2,3,3,4];
function f(arr, z) {
arr[0] = 'a';
arr = ['a', 'b']
}
f(a);
console.log(a);
[ 'a', 0, 1, 1, 1, 2, 2, 3, 3, 4 ]
From within
f()
function, the linearr[0] = 'a'
modifiesarr
in the outer scopeBut the reference arr =
(without a
letor
const`) should also refer to outer scope?