-1

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?

Kyle Vassella
  • 2,296
  • 10
  • 32
  • 62

1 Answers1

5

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.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Thanks a lot. Elegantly explained - I'm surprised I didn't know this at 2 months in. Sorry for posting a duplicate question - I tried Google first but somehow missed it. Downvotes have crushed my soul, no more posts from me for a while :/ – Kyle Vassella Aug 26 '16 at 05:08
  • Don't worry about a single downvote; also, if you haven't been here a while, you are not be expected to know that someone wrote the answer to the same question before; I didn't know myself, so I answered. – Amadan Aug 26 '16 at 05:14