omkaartg
omkaartg

Reputation: 2777

What is the Difference between function and function() When I call them in javascript?

I had a question before and a person answered it very well, My code works now, But I didn't completely understand the answer. This is the coding bit that I didn't understand -

document.getElementById("myButton").onclick = words;

Now I already had defined function words(). My mistake was that I had written words() instead of words. So what is the difference between calling of words() and words ?

Upvotes: 3

Views: 91

Answers (3)

Amit Wagner
Amit Wagner

Reputation: 3264

Doing:

document.getElementById("myButton").onclick = words;

this means:

put a pointer to the function and when the event fires it will call the function. When you do words() you call the function.

Upvotes: 1

Quentin
Quentin

Reputation: 943097

words evaluates as a function.

words() calls that function and evaluates as the resulting return value.


The value you assign to onclick needs to be the function you want to get called when the click happens.

If you want the words function to be called, you have to assign that.

Upvotes: 4

Shubham Khatri
Shubham Khatri

Reputation: 281606

The difference between words and words() is that in the first case you are referencing the function and in the second case you are calling it

so when you do

document.getElementById("myButton").onclick = words;

you are assigning a function words to the onclick listener, while if you do

 document.getElementById("myButton").onclick = words();

you are actually assigning the evaluated value of words to the onclick listener. onclick needs to be assigned a function which will be called when an onclick event happens.

Upvotes: 2

Related Questions