2

Why does JavaScript treat the scope of an array differently than it does the scope of other variables? Typically, if one passes a variable in a global scope into a function as a parameter, it is then local and changing it within the function does not change the value of the global variable. For example:

var globalInt = 1;
function test1(x){
    x = x + 1
}
test1(globalInt);
console.log(globalInt); //globalInt is still 1

However, it appears the same does not apply when passing an array of values.

var globalArray = ["TEST"];

function test(x){
    x[0] = x[0].toLowerCase()
}

test(globalArray);

//globalArray is now ["test"] instead of ["TEST"]
console.log(globalArray[0]);

This happens for me when I test in Chrome, but I have not tested it in other browsers so far. Why does this happen and does it happen in other browsers?

Joshua Dannemann
  • 2,003
  • 1
  • 14
  • 34

2 Answers2

3

This is simply because an array (which is an Object) are passed by reference while primitives are not. Note that technically it is passed by value but in this case that value is a reference, thanks Esteban

A object is automatically passed by reference, without the need to specifically state it

If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function, as shown in the following example:

MDN Link

omarjmh
  • 13,632
  • 6
  • 34
  • 42
  • 2
    Technically it's still passed by value the value in this case just happens to be a reference to the array. – Esteban Felix Apr 25 '16 at 22:49
  • Hmm... seems if JavaScript is going to implicitly pass variables by ref, then there should be a way to explicitly pass by val or by ref depending on what is desired. In any case, the workaround is to clone the array first. Thanks for the answer! – Joshua Dannemann Apr 25 '16 at 22:53
  • just to be clear check this out: http://stackoverflow.com/questions/7744611/pass-variables-by-reference-in-javascript – omarjmh Apr 25 '16 at 22:54
1

Yes... JavaScript objects and arrays (which are objects) are passed by reference. But you should remember to read the method signature explicitly because some array methods don't alter the original array but return a new one. Read the MDN documentation carefully about the method in question. Array.prototype.map() would actually leave the original array intact and return a brand new array which you'd need to set to assign to a variable.

Marko
  • 21
  • 1
  • 4