0

I am new to JavaScript. I read a code which is:

document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}

I read the documentation, in this I get that the second parameter of addEventListener would be a function like the bellow (here after function we use () brackets)

document.getElementById("myBtn").addEventListener("click", function(){
document.getElementById("demo").innerHTML = Date();
});

according to my knowledge, we must use () after a function which is not in the first example. Even if I use than it doesn't work. So my question is why we can't use () if we create a separate function. I hope you understand my question.

1 Answer 1

3

The parentheses mean different things in these scenarios. The parentheses that go after the function keyword denote a list of arguments that you provide to the function, e.g. function(a, b, c) signifies that the function takes 3 arguments, a, b, and c. The parentheses that go after displayDate represent the fact that you are calling the function with no parameters, and passing the return value to addEventListener. Since displayDate returns undefined, you are essentially setting undefined as an event listener, which will do nothing.

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

2 Comments

thanks for answer ... but if i do this than it also not work as it expected to do. var test = "hello" document.getElementById("myBtn").addEventListener("click", displayDate(test)); function displayDate(param) { document.getElementById("demo").innerHTML = Date(); alert(param) }
Well yes because you're still calling the function, and it's not returning another function. addEventListener requires a function as the second argument, not the value that you get from calling a function.

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.