-1

Inside a function, I'd like to change the value of a global variable that is specified by the function's argument.

A = 1;
B = 2;
C = 3;

function myFunction(variable) {
    variable += 10;
}

myFunction(A);
myFunction(B);
myFunction(C);

I'm looking for these results:

console.log(A);   // 11 expected
console.log(B);   // 12 expected
console.log(C);   // 13 expected

I can't output the new value via a return statement because it's computed inside the callback function of a post request.

How to achieve this?

Lord Dark
  • 11
  • 2
  • `0 + 10 != 11`!!! – Mamun Aug 04 '19 at 09:59
  • It's not possible. This is called `shadowing`, that's that your argument is other variable than global, so A in `myFunction` is other that A in `global` – Dominik Matis Aug 04 '19 at 10:03
  • 1
    @DominikMatis technically speaking this is not shadowing: the thing is that JavaScript always pass by value, not by reference. – Gerardo Furtado Aug 04 '19 at 10:06
  • Yes, pretty easily: `function myFunction(variable) { window[variable] += 10; } myFunction('A'); myFunction('B'); my Function('C');` – melpomene Aug 04 '19 at 10:07
  • @Quentin is correct, there is a clue in [the value/reference question](https://stackoverflow.com/a/3638034/673991). But it's buried, and that's more about a language technicality that one might not know to ask for. This question is directed toward a functional need. (As is this [parameter output](https://stackoverflow.com/q/3175687/673991) question, though the need is subtly different.) Future searches might usefully lead here, so I'll **vote to reopen.** Better answer: `A = {value:0}` etc. then in myFunction `variable.value += 10` – Bob Stein Aug 04 '19 at 17:29

1 Answers1

-5

It's not possible. This is called shadowing, that's that your argument is other variable than global, so A in myFunction is other that A in global

Maybe trying to run with apply() and using this.variable inside function would help

Dominik Matis
  • 2,086
  • 10
  • 15