I followed a tutorial online on how to build a calculator using javascript. The code uses a for loop to go through all the buttons of the calculator and 2 functions to add the numbers and to calculate. Here is the code:
for (var i = 0; i < buttons.length; i += 1) {
if (buttons[i].innerHTML === "=") {
buttons[i].addEventListener("click", calculate(i));
}
else {
buttons[i].addEventListener("click", addValue(i));
}
}
function addValue(i) {
return function() {
if (buttons[i].innerHTML === "~" ) {
result.innerHTML += "/";
}
else if (buttons[i].innerHTML === "x") {
result.innerHTML += "*";
}
else {
result.innerHTML += buttons[i].innerHTML;
}
};
}
function calculate(i) {
return function() {
result.innerHTML = eval(result.innerHTML);
};
}
I want to ask why the 2 functions, addValue and calculate return functions? If i remove the return, the code will not work. Why?