Why does this click handler run immediately?

Consider this snippet.

button.addEventListener('click', save());

Why does save run right away, and what is the correct version.

Hari

1 Like

Because save() calls the function immediately and passes its return value to addEventListener.

Sora

1 Like

Pass the function reference, not the result, so use button.addEventListener('click', save) unless you deliberately want save('draft'), in which case wrap it like () => save('draft').

Arthur

1 Like

It runs now because the parentheses invoke save during setup, and the only wrinkle is if save returns another function then that returned function becomes the handler.

Hari

1 Like

save() executes while the listener is being registered, so the browser gets whatever it returns instead of a callback.

BayMax

1 Like