I'm building a calculator. Why is the addToStr function not able to change the values of the global variables? (I sampled just some switch-statement cases to shorten the code).
window.onload = function () {
$(".buttons").click(function () {
var id = $(this).attr("id");
switch (id) {
case "b-7":
value = "7";
console.log(value);
addToStr(miniDisplayString, value);
addToStr(numberString, value);
break;
case "b-8":
value = "8";
addToStr(miniDisplayString, value);
addToStr(numberString, value);
break;
case "b-9":
value = "9";
addToStr(miniDisplayString, value);
addToStr(numberString, value);
break;
case "b-divide":
value = " / ";
addToStr(miniDisplayString, value);
break;
}
console.log("total = " + total);
console.log("miniDisplayString = " + miniDisplayString);
console.log("numberString = " + numberString);
});
}
var total = 0;
var value;
var miniDisplayString = "";
var numberString = "";
function addToStr(tot, val) {
tot += val;
}
You cannot pass values by reference in javascript, it thinks you are simply trying to use the variables' value. In order to do so, you would need to use pointers, which are not available in a language like javascript. In order to achieve this by using your current method, you would need to create a global variable for each reference, and set them each time with a different function. (You would need a separate function per variable, and only take 'value' as an argument; and set the variable to the corresponding value passed to the function 'addTo<varName>'). However, this method seems unnecessary and highly inefficient. Just setting them manually in your code, wouldn't hurt at all; Like so:
... instead of using a separate function for each and every reference, which is honestly not necessary at all, not in your case nor in general. You can also return the new value in the function and use that, but again; not necessary at all.