0

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.

tazboy
  • 1,685
  • 5
  • 23
  • 39
  • In the first you are passing a function to `addEventListener` and in the second you are passing `undefined` (the return value of `setCounter()`). Let me ask you a simple question. You should understand it if you have programmed in any programming language before. If I have a function `x()` that returns the value `5` and I do `console.log(x())` do you expect it to print a function or `5`? – slebetman Sep 11 '22 at 03:31
  • 5. Are you suggesting that the arrow notation for `const setCounter` is returning multiple lines? Please explain. – tazboy Sep 11 '22 at 14:52
  • In javascript if a function has no `return` statement at the end it returns the value `undefined`. Your `setCounter()` function returns `undefined`. The `const setCounter` statement assigns that function to the variable `setCounter` – slebetman Sep 11 '22 at 15:12
  • Do you understand the difference between `setCounter` and `setCounter()`? The value of `setCounter` is a function while `setCounter()` calls that function and returns the value `undefined` – slebetman Sep 11 '22 at 15:13
  • So both `function setCounter` and `const setCounter` work just fine with no parameters when passing `setCounter` inside of `addEventListener`. The part I seem to have been misunderstanding was why the arrow function in `() => setCounter(++counter)` was needed. Correct me but the `() =>` is to allow passing the function, with parameters, as a reference much like with passing `setCounter` with no parameters? – tazboy Sep 11 '22 at 15:36

1 Answers1

0

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)})