0

I often see event listeners generated in the form of

var target = document.getElementById('target');
target.addEventListener(type, event);

But it seems equally reasonable to just write

document.getElementById('target').addEventListener(type, event);

Is there a benefit to creating a variable? Am I missing something? I'm willing to bet I'm missing something.

Thanks, I'm super new at this.

  • I do that whenever I need to use `target` inside the event handler, so I don't have to re-fetch it (thus improving performance). – Siguza Jul 07 '16 at 16:28
  • @Siguza, Using `this` in callback will give you the `element`.. If you are using variable twice, better cache it in `variable` – Rayon Jul 07 '16 at 16:29
  • 1
    DOM lookups are terrible for performance. If you need to reference the same element more than once in your code then it is beneficial to store the reference in a variable. – Malk Jul 07 '16 at 16:31

1 Answers1

1

No, you are not missing anything. You can use any form you like. Basically, the variable should be used only if you need to use the target element more than once (e.g. you need to bind more event handlers ):

var target = document.getElementById('target'); target.addEventListener(type, event); target.addEventListener(type1, event1);

Otherwise, this is the way to go:

document.getElementById('target').addEventListener(type, event);

Mohit Bhardwaj
  • 9,650
  • 3
  • 37
  • 64