JavaScript function expression works but function declaration does not

Viewed 35

I'm checking out using Vite for my bundler and there's some code in there that is used to update a counter when clicked. Here is what it shows:

export function setupCounter(element) {
  let counter = 0

  const setCounter = (count) => {
    counter = count
    element.innerHTML = `count is ${counter}`
  }

  element.addEventListener('click', () => setCounter(++counter))
  setCounter(0)
}

I tried changing it to something I'm more familiar with:

export function setupCounter(element) {
  let counter = 0

  function setCounter(count) {
    counter = count
    element.innerHTML = `count is ${counter}`
  }

  element.addEventListener('click', setCounter(++counter))
  setCounter(0)
}

which I thought be would equivalent, but it's not updating the counter when I click the button. What did I mess up or what am I misunderstanding?

Update:

Not the same question as Why does click event handler fire immediately upon page load? since this has a parameter. I'm also wondering why an arrow function seems to be needed as opposed to used by preference.

1 Answers

In your second example you try to initially call the callback function which results in calling it just once at initial run.

element.addEventListener('click', setCounter(++counter))

Try to either pass the reference to it or, if you need to prefix-increment the counter, use an arrow function.

element.addEventListener('click', () => { setCounter(++counter)})
Related