My code increments a number up or down by 1. The problem is "testNum" which is a global variable should reflect the increments up or down but when I check the value of "testNum" in the console it's always 20. I pass "testNum" to my function and return it. Why isn't it reflecting the increments?
Fiddle: http://jsfiddle.net/FnUXw/1/
<input type="button" id="btnDown" value="-">
<span id="amountDiv">amount div</span>
<input type="button" id="btnUp" value="+">
<script>
var testNum = 20;
amountDiv.innerHTML = testNum;
function makeButtonIncrement(button, upDown, displayDiv, variable) {
function changeValue () {
if (upDown == "up") {
variable++;
}
if (upDown == "down") {
variable--;
}
displayDiv.innerHTML = variable;
}
button.onclick = changeValue;
return variable;
}
makeButtonIncrement(document.getElementById('btnDown'), "down", document.getElementById('amountDiv'), testNum);
makeButtonIncrement(document.getElementById('btnUp'), "up", document.getElementById('amountDiv'), testNum);
</script>
Numbers are passed by value, not by reference so you can't do what you're trying to do that way. With your code structured the way it is, you could do it like this where you assign the return value:
testNum = makeButtonIncrement(document.getElementById('btnDown'), "down", document.getElementById('amountDiv'), testNum);
Only arrays and objects are passed by reference so they can be passed as arguments and have the function modify the original variable. Other types are passed by value (e.g. a copy is made for the argument) so you cannot modify the original.
The work-around to modify the original is to pass it as a property of an object. Then, because the object is passed by reference, the function can modify the original property value.
Or, since you're already using a global variable, you could just modify the global variable directly and not even pass it as an argument. It is the passing as an argument that makes a copy of it so you can't modify the original. Global variables are, in general, not recommended, but if it's already global for other reasons, you can just modify it directly in your function without passing it as an argument.