Spot the bug - #100: Save Button Click

Quick one: event handling bug here.

const button = document.querySelector('#save');
button.addEventListener('click', saveForm());

function saveForm() {
  console.log('saved');
}

Reply with what is broken and how you would fix it.

Calling saveForm() right there runs it immediately and passes its return value (undefined) as the handler.

button.addEventListener('click', saveForm);

No parens, just pass the reference. Classic one, I still catch myself doing this occasionally when refactoring in a hurry.

Spot the Bug answer: saveForm() is called immediately and its return value (undefined) is passed as the click handler, so saveForm never runs on click.

The fix:

button.addEventListener('click', saveForm);

Why:
Using saveForm() invokes the function right away during setup instead of passing a reference to it. addEventListener needs a function reference, not the result of calling the function, so the click event has no valid handler attached.