3

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 ?

asked Dec 1, 2017 at 11:14
4
  • word() will execute the function, word will hold the reference to the function which you are assigning to onclick handler. Commented Dec 1, 2017 at 11:16
  • Well words doesn't call them. Commented Dec 1, 2017 at 11:18
  • 1
    Possible duplicate of js difference between foo(), foo and function(){foo()} Commented Dec 1, 2017 at 11:26
  • Do you know what the meaning of var bar = foo(); is? What the value of bar will be? Commented Dec 1, 2017 at 11:27

3 Answers 3

4

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.

Bergi
671k162 gold badges1k silver badges1.5k bronze badges
answered Dec 1, 2017 at 11:16
Sign up to request clarification or add additional context in comments.

Comments

2

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.

answered Dec 1, 2017 at 11:17

Comments

1

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.

1stthomas
1,0082 gold badges19 silver badges28 bronze badges
answered Dec 1, 2017 at 11:17

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.