0

I have button and want to add EventListener to this button. Question is: what is the best way to code it?

v1:

let BackBtn = document.querySelector('.back');
BackBtn.addEventListener('click', load_from_breackpoint);

v2:

document.querySelector('.back').addEventListener('click', load_from_breackpoint);

Note: BackBtn dont used in code bellow. In my project so much buttons like this and may it affect performance if I use v1 for 30 buttons?

Dimabytes
  • 526
  • 1
  • 6
  • 17
  • 1
    These are equivalent, neither is more performant than the other. –  Nov 27 '19 at 21:00
  • It won't affect performance by any reasonable amount, but having so many buttons will make the code ugly, and code clarity should be the most important thing to strive for in most situations. Consider using a different method to make the code more DRY – CertainPerformance Nov 27 '19 at 21:00
  • 1
    If you have lots of buttons that need the same listener, give them all the same class, use `querySelectorAll()`, and use a `forEach` loop to add the listener to each of them. – Barmar Nov 27 '19 at 21:02
  • I had different buttons and different functions for them – Dimabytes Nov 27 '19 at 21:03
  • As mentioned by Barmar, you cannot use v1 for 30 elements. `querySelector()` only returns one Element, so that criteria is a mute point. Worst case scenario, the variable is in a global scope and you arbitrarialy have a lingering variable that you're not using. Not a big performance concern. – Taplar Nov 27 '19 at 21:12

2 Answers2

1

v2 is perfectly fine, no performance will be noticeably lost even if u had 100 buttons and v1, but v2 is generally more edit-friendly and will require less time to maintain, re-read and/or change your code. use v2. less code is always better IFF you can read it fine.

Max Alexander Hanna
  • 3,388
  • 1
  • 25
  • 35
-2

What about this:

const $ = document.querySelector; // Since you don't use jquery
$('.back').addEventListener('click', load_from_breackpoint);
Fabien
  • 45
  • 5
  • 1
    This does not answer the question, and making code look like jQuery, when it isn't *actually* jQuery, is setting yourself up for future defects. See the [Principle of Least Astonishment](https://en.wikipedia.org/wiki/Principle_of_least_astonishment) –  Nov 27 '19 at 21:15