Search code examples
javascriptjqueryconstants

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

  • 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 if $myDiv is a const
    $myDiv.doThing2();
    

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