1

I’m trying to make a button that changes a global variable.

HTML

<script src='script.js'><script>
<button onclick = "myFunction(a)>Increase A</button>
<button onclick = "myFunction(b)>Increase B</button>

JavaScript

var a = 0;
var b = 0;
function myFunction(variable){
    variable += 1;
}

I’m trying to make a/b increase, but it doesn’t have any effect. I think it is only changing a copy of the variable. Is it possible to fix this?

Edit: It doesn’t seem to work for let. Is it possible with let as well?

Joshiepillow
  • 227
  • 1
  • 12

2 Answers2

3

You could treat those two variables as keys on the window object, and pass the name of the variable to your function:

var a = 0;
var b = 0;
function myFunction(variable){
    window[variable] += 1;
    console.log(a,b)
}
<button onclick = "myFunction('a')">Increase A</button>
<button onclick = "myFunction('b')">Increase B</button>

Though it may be better to use your own object container instead of depending on window:

var myData = {a: 0, b: 0};

function myFunction(variable){
    myData[variable] += 1;
    console.log(myData.a, myData.b)
}
<button onclick = "myFunction('a')">Increase A</button>
<button onclick = "myFunction('b')">Increase B</button>
...or, indeed, to not depend on global variables at all, depending on what you're trying to accomplish here.
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
0

In JavaScript, non-object arguments are passed in by value, so what you're doing here is passing in the value of a and b, not a reference to the variable themselves. Instead, you can refer to these variables by name, and access them on the window object, like this:

JavaScript:

function myFunction(variable){
    window[variable] += 1;

    console.log(a, b)
}

HTML:

<button onclick = "myFunction('a')">Increase A</button>
<button onclick = "myFunction('b')">Increase B</button>
Casey Rule
  • 2,085
  • 2
  • 18
  • 28