Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

const, let or none for addeventlistener, what would be correct?

So I have been searching around, but was unable to find any mentions of this.

If I want to add an "EventListener" to an element, what would be the "correct" way?

    const myHtmlElement = document.getElementById("my-id");
    myHtmlElement.addEventListener("change", function(e){ do stuff });

Or should i use let for this instead? Since I’m "adding" an eventlistener?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Or would it more correct to simple do

document.getElementById("my-id").addEventListener("change", function(e){ do stuff });

>Solution :

Use const since you are not doing reassignment of variable.

Const does not mean the value it holds is immutable, it means that the variable identifier cannot be reassigned.

First approach has better readability so go with that definitely.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading