0

I am learning JS,and I have an example which I don't understand. When we call functions like this it works:

       <button onclick="displayDate()">Try it</button> 

This also works:

   <script>
        document.getElementById("myBtn").onclick = displayDate;

        function displayDate() {
         document.getElementById("demo").innerHTML = Date();
        }
  </script>

But when I change this displayDate to displayDate() it shows me the date when page is loaded,so onclick doesn't work. My question is: why does JS DOM work like this? What is really happening? Do we not call a function like this: function();?

1 Answer 1

1

When you write:

something = functionName();

it means to call the function immediately, and then put the value that it returns into something.

When you write:

something = functioName;

it means to put a reference to the function into something, but not call it. This allows the function to be called later, using that reference. When something is someElement.onclick, this happens when the user clicks on the element.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.