2

I'm currently learning JavaScript and was learning about callback functions.

My question is that what is better to use, when passing a function to addEventListener.

addBtn1.addEventListener('click', function() {
    console.log('inline'); //inline
})

addBtn2.addEventListener('click', () => {
    console.log('anonymous inline'); //anonymous
})

const doSomething = function() {
    console.log('do something')
}

addBtn3.addEventListener('click', doSomething); //named function

Since each function is an object, every time I press addBtn1 and addBtn2, will new functions be created in Memory?

Also if we want to pass some parameters, what is better to use .bind() or the inline approach? Considering I understand the behavior of this in anonymous vs normal inline function.

  • 3
    Technically, the best for performance is to use [event delegation](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation). However, in practice, it rarely matters that much. Unless you have A LOT of listeners, it's all the same whether they are arrow functions, normal functions or whatever. – VLAZ Oct 20 '20 at 17:40
  • 1
    The first two are *both* anonymous functions, it's just that one is an arrow function and the other a "regular" function expression. Unless you use `this` inside the function, it doesn't matter which you use, so it's purely personal preference/coding style. As for the third, again it's basically opinion whether you prefer this or not (with the caveat that a named function like this is necessary if you need to refer to it elsewhere - for example, to remove it as an event handler). I'm going to vote to close this as it's a matter of opinion, therefore off-topic here. – Robin Zigmond Oct 20 '20 at 17:50
  • 1
    Oh I just realised you asked about performance. No idea which would perform best, but I'm pretty sure that, whatever performance problems you might get in a real app, the real issue won't be which of these 3 forms you use for event handlers! – Robin Zigmond Oct 20 '20 at 17:54

0 Answers0