Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Interactive Web Pages with JavaScript Selecting Elements and Adding Events with JavaScript Perform: Event Handling

Grace Kelly
Grace Kelly
33,990 Points

Why does addTask() load the function straight away even with an onclick event handler?

Hello my fellow students and Andrew Chalkley, i'm just wondering why does the following cause the function to load even when the button HASN'T been pressed?

var addTask = function () {
  console.log("Add task...");
}

addButton.onclick = addTask();

while removing the () causes it to load only when the button has been pressed??

var addTask = function () {
  console.log("Add task...");
}

addButton.onclick = addTask;

I understand that you don't need the '()' because you have already declared the function i.e it's not anonymous...I think what's confusing me is the fact is there is an event handler before it...shouldn't that control when the function executes??

Thanks in advance for any explanation!!

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

When you add the () to a function call, it will immediately call that function when the compiler reaches it (regardless or what was before it... i.e. your event handler).

That's why the code works fine when you remove the (). Now the function waits for (and is dependent) on the event handler to trigger it.

I guess you could think about it as a video on a website. It can have a "Play" button, but if "auto-play" is enabled, it doesn't wait for the play button to be pressed... it just plays.

Hope that cleared it up a little. Jason :)

Grace Kelly
Grace Kelly
33,990 Points

thanks Jason, that clears things up! :)