Can anyone help explain the under hood of the following three examples(they have puzzled me a long time and I can't find an answer by google)? Why they produce complete different results?
Example 1.
I created a global variable named myArray
and directly changed its value with a function. Everything is going on as expected. I changed the value of 'myArray'.
var myArray = [1, 2, 3, 4, 5];
function alterArray(){
myArray = [5, 4, 3, 2, 1]
return myArray;
}
alterArray();
console.log(myArray); //-> Array(5)[ 5, 4, 3, 2, 1 ]
Example 2.
To make the alterArray
function more efficient, I added a parameter to it so that the function can change any global variable into an array [5, 4, 3, 2, 1]. Then the function just doesn't work. myArray
is still [1, 2, 3, 4, 5]. Why? What happened?
var myArray = [1, 2, 3, 4, 5];
function alterArray(arr){
arr = [5, 4, 3, 2, 1];
return arr;
}
alterArray(myArray);
console.log(myArray); //--> Array(5)[ 1, 2, 3, 4, 5 ]
Example 3.
I changed arr = [5, 4, 3, 2, 1];
into arr[0] = "number one";
(inspired by an exercise in chapter 4 Eloquent Javascript) in the function. And the function works again! Why? Why the function doesn't work when I assign myArray
a complete new value via the parameter, but works well when I only change part of myArray
via the parameter?
var myArray = [1, 2, 3, 4, 5];
function alterArray(arr){
arr[0] = "number one";
return arr;
}
alterArray(myArray);
console.log(myArray); //--> Array(5)[ number one, 2, 3, 4, 5 ]