Kyle Vassella Kyle Vassella - 3 months ago 7
Javascript Question

Calling functions inside of loops and methods doesn't require ()?

Why don't I need to use

()
to call a function within a 'for' loop or within an '.addEventListener()' method? For example:

function activitiesReset()
{activitiesLegend.style = '';
}

for (var i=0; i<checkboxes.length; i++) {
checkboxes[i].addEventListener('change', activitiesReset);
}


In the addEventListener method, I first tried calling my function like
activitiesReset()
, but this did not work. Removing the
()
from the end of the function worked.

Why is that?

Answer

checkboxes[i].addEventListener('change', activitiesReset) is not calling activitiesReset. It is passing activitiesReset as an argument. activitiesReset is a function itself; activitiesReset() is a call to a function, evaluating to its return value. You want to set the event listener to your function, not to undefined (which is the result of calling your function).

The key to understanding this is the fact that functions in JavaScript are also values, just like numbers or strings or objects. (In fact, they are a specific kind of object.)

var adderFuncValue = function(x, y) { return x + y; };
function multiplierFuncValue(x, y) { return x * y; };

function callFuncWithTwoParams(func, p1, p2) {
  func(p1, p2);
}

callFuncWithTwoParams(adderFuncValue, 3, 5); // 8
callFuncWithTwoParams(multiplierFuncValue, 2, 3); // 6
var someFunc = adderFuncValue;
someFunc(7, 8); // 15

So just like I'm passing functional values into callFuncWithTwoParams, you are passing a functional value into addEventListener. The browser will remember that function and associate it with change event, and call it -- later.

Comments