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

Perform: Event Handling

In this code: addButton.onclick = addTask; why after addTask there isn't ()?

3 Answers

Vittorio Somaschini
Vittorio Somaschini
33,371 Points

Ok.

If you use the first method you would still need to put parenthesis when calling the function on the click to actually call the function.

With the second piece of code you do not need () as you are setting up a variable called addTask which has the function call inside it so :

if -> function addTask() {...}; we go with: addButton.onclick = addTask()

if -> var addTask = function() {...}; we go with: addButton.onclick = addTask in the second case

I hope this makes it clear.

;)

Vittorio

Thanks, your answer is clear and helpful.

Henrik Hansen
Henrik Hansen
23,176 Points

When adding the parentheses to the .onclick = ... the code will be executed when loaded. The exception to this is when using an anonymous function with the onclick.

// executed when line is loaded:
button.onclick = addTask();

// Executed at the onclick event:
button.onclick = addTask;

// Anon function executed at onclick event:
button.onclick = function () { 
  addTask();
};

Thanks for answer.

Vittorio Somaschini
Vittorio Somaschini
33,371 Points

Hello Chuong.

I do not remember the specific case but I guess in this case addTask is a variable and the function call is inside it.

At the top of your code you (and teacher) should have initialized it as a function.

So then we do not need to put parenthesis again.

Is it the case?

Vittorio

In the video, the teacher does present two ways of writing function:

function addTask() {...};

and

var addTask = function() {...};

I think this could be the reason whether () could be added or omitted after addTask in the addButton.onclick = addTask;

What you think?