0

Is there a way to change a variable used as a function argument within the body of the function? For instance:

var global = 1;

function modifyGlobal(arg) {
  arg = 2;
}

modifyGlobal(global);
console.log(global); // Results in 1

Obviously this code doesn't work, but I'd like to get the console.log(global) to result in 2, effectively changing the global variable.

Edit: In the answer linked as a duplicate question, it states that you cannot do this in javascript, however, in Eloquent JavaScript, there is an exercise asking for this type of thing to be done, and provides the running code for it:

var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]

So, in this example, they are passing an array to this and directly modifying that array. Per the question asking about pass variables by reference, the answers imply you can't do this.

bpoinder85
  • 35
  • 6
  • The difference between the `reverseArrayInPlace` example and what you're trying to do, is that it's modifying an array, not reassigning a variable. `arrayValue` is still the same array before and after the function call, it's just been modified. What you're trying to do is reassign `global`, which you can't do (and you can't modify it, because numbers are immutable in JavaScript). – Matthew Crumley Sep 28 '17 at 22:17
  • So the [accepted answer](https://stackoverflow.com/a/7744623/2214) is correct, and the first suggestion is about the closest you can get. You'll need to change `global` to be a property of an object, then pass the object to your function and modify that. – Matthew Crumley Sep 28 '17 at 22:20

0 Answers0