0

I was learning javascript event handling when I ran into something weird.

When I wrote my onclick event listener as

.addEventListener("click", alert('button clicked'))

it alerted immediately

searching online the fix seems to be to wrap it inside of a function like this

addEventListener("click", function(){ alert('button clicked')}

It was quite confusing since it looks like both versions bound the click to an action. Except the second one has an extra layer wrapped around it.

Is the reason for this behavior because js is compiling and running the line immediately after it read it? But then wouldn't the function also run as well?

llssff
  • 117
  • 6
  • 1
    That's because the second argument of `addEventListener` has to be a `function` for deferred execution. If you don't wrap `alert` in a function it is just executed when reaching the line `addEventListener("click", alert('button clicked'))` and `addEventListener` receives `undefined` as second parameter which is not a listener at all – Guerric P May 08 '21 at 19:52
  • Read up on how "callbacks" work – charlietfl May 08 '21 at 19:55
  • The arguments to a function are always evaluated before the function is called. So your first version calls `alert()` *before* calling `addEventListener()` – Barmar May 08 '21 at 19:56
  • See also [When do I use parenthesis and when do I not?](https://stackoverflow.com/q/7969088/215552) – Heretic Monkey May 08 '21 at 20:00
  • If you have `foo(bar())` then `bar` will be called first and its return value will be passed to `foo`. Arguments are always evaluated first, like in most languages, this is not some special behavior in JavaScript. `function(){ alert('button clicked')}` *creates* a function value, it doesn't call, just like `"foo"` creates a string value. – Felix Kling May 08 '21 at 20:44

0 Answers0