What is the point of returning a function in this specific javascript code? -


i followed tutorial online on how build calculator using javascript. code uses loop go through buttons of calculator , 2 functions add numbers , calculate. here code:

for (var = 0; < buttons.length; += 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 ask why 2 functions, addvalue , calculate return functions? if remove return, code not work. why?

if remove return statement addvalue returns undefined.

addeventlistener expects 2 arguments, name of event run function on, , function run.

if addvalue returns undefined passing undefined addeventlistener instead of function.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -