Reputation: 2777
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
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
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
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