Should this code be using function(), (e) => or () =>?

If all these work,

Which should it be using?

.addEventListener('click', function()

.addEventListener('click', (e) =>

.addEventListener('click', () =>

Code 1
https://jsfiddle.net/xnwr5jeq/152/

<script>
  document.querySelector('.sent').addEventListener('click', function() {
    const player = document.querySelector('.player');
    const value = document.querySelector('.input');
    player.volume = 1.0;
    player.src = value.value;
  });
</script>

Code 2:
https://jsfiddle.net/xnwr5jeq/154/

<script>
  document.querySelector('.sent').addEventListener('click', (e) => {
    const player = document.querySelector('.player');
    const value = document.querySelector('.input');
    player.volume = 1.0;
    player.src = value.value;
  });
</script>

Code 3:
https://jsfiddle.net/xnwr5jeq/157/

<script>
  document.querySelector('.sent').addEventListener('click', () => {
    const player = document.querySelector('.player');
    const value = document.querySelector('.input');
    player.volume = 1.0;
    player.src = value.value;
  });
</script>

Since you dont need the event you can go by the third. But I always type in the event param in my handlers, incase you need it later on.

1 Like

I agree the third 8s best. In general, a fat arrow is better than a function - less memory. There are some slight differences, but it won’t matter here.

1 Like

What were the slight differences you were thinking of?

The big one is that they don’t create their own this but inheret it from yhe lexical scope - which is why it ia a tad faster. But 8n most cases they can be interchangeable.

1 Like