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

Can I use const to assign jQuery or should I use let?

When I save a jQuery result to a variable so that I can reuse it later, can I declare that variable const? Or is there something about the internal workings of jQuery that makes it better for me to use let?

const $myDiv = $("#myDiv"); // will I be sorry later that I used const instead of let?
$myDiv.doThing1();
$myDiv.doThing2();

>Solution :

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

Using const is perfectly acceptable. The main reason you’d use let instead would be if you wanted to reassign $myDiv, something like:

let $myDiv = $("#myDiv"); // will I be sorry later that I used const instead of let?
$myDiv.doThing1();

$myDiv = $("#myOtherDiv") // this will break at you if $myDiv is a const
$myDiv.doThing2();

When $myDiv is a const, it doesn’t prevent you from mutating it, just from reassigning it.

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