0

Can someone explain why operating on an array reference (arr) inside a function (nextInLine) changes the values in the global array when I haven't done anything (that I know of) to operate on the global array globalArr from within my function?

I thought operating in a function with values passed to said function was basically like operating on local variables and that I'd have to reference the global variable from within the function or return a value if I wanted to make those values accessible outside the function.

https://codepen.io/jakeNesom/pen/eWMXdP?editors=1111

function nextInLine(arr, item) {


  arr.push(item);
  item = arr.shift();
  return item ;  
}

// Test Setup
var globalArr = [1,2,3,4,5];

// Display 
console.log("Before: " + JSON.stringify(globalArr));
console.log(nextInLine(globalArr, 10)); // Modify this line to test
console.log("After: " + JSON.stringify(globalArr)); 
Jake
  • 31
  • 10
  • Possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – rmalviya May 12 '17 at 04:33

2 Answers2

0

This is because you pass an object (globalArr) to the function. When you pass an object, you pass reference to it. However, the default mechanism in JavaScript is to pass by value. This why your orifginal value of the array changes as well when you modify it the function.

Nurjan
  • 5,889
  • 5
  • 34
  • 54
0

Javascript is pass by value so when you invoke your function like this

nextInLine(globalArr, 10)

The globalArr reference that is passed into that function points to the same location where you have initilised your array.

Hence when inside your nextInLine function you call

arr.push(item);

You have pushed an item into your global array.

I think what you were mistaking was the variables declared within a fucntion only being in the scope of a function unless you return a reference to them e.g

function foo(){
  var a = 10;
  console.log(a); //10
}
console.log(a); //undefined
derp
  • 2,300
  • 13
  • 20
  • Thank you for the thorough explanation - I didn't realize that objects passed to functions were references – Jake May 12 '17 at 21:43