0

I'm trying a book problem in "eloquent JavaScript" and noticed a quirk with arrays that I would like to understand. It appears the "global" array can only be changed by index. Why is that? Any benefit?

I assume when passing an array to a function we are passing by reference. My assumption is that if you change the Array in the function it will change the value of that "global" Array in the accessing code block that called the function.

    function changArr(arr) {
      arr = ["eee"];
      return(arr);
    }

    var arr = [0,1,2,3,4];
    console.log(changeArr(arr)) //eee
    console.log(arr) // [0,1,2,3,4]


function changArr(arr) {
      arr[0] ="eee";
      return(arr);
    }

    var arr = [0,1,2,3,4];
    console.log(changeArr(arr)) //['eee',1,2,3,4]
    console.log(arr) // ['eee',1,2,3,4]
AmericanCities
  • 139
  • 1
  • 10
  • In neither case are you modifying a global variable. A function parameter creates a new variable, scoped to that function. – lonesomeday Aug 05 '16 at 18:36
  • Thanks zzzzBov for the link. I understand now. Objects are passed to functions as a reference value and not the reference/pointer itself. – AmericanCities Aug 05 '16 at 19:04

0 Answers0