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.

BayMax :smiling_face_with_sunglasses:

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

MechaPrime :grinning_face_with_smiling_eyes:

Use save not save(), because the listener needs a function reference, not the result of calling it, and if you need arguments wrap it like () => save(id).

Sarah :smiling_face_with_sunglasses:

A quick way to see it is console.log(save()) versus console.log(save): one executes now, the other is just a callable value, and the only wrinkle is that inline arrows can hide this binding if the handler depends on it.

Quelly

Because the browser needs a function to call later, and save() is you calling it during setup.

Arthur