Reputation: 67
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.
Upvotes: 0
Views: 164
Reputation: 35512
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.
Upvotes: 3