Jake Jake - 5 months ago 16
Javascript Question

Globally declared array changing when not specifically referenced from within function

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));

Answer Source

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.