Home > Enterprise >  Can I use const to assign jQuery or should I use let?
Can I use const to assign jQuery or should I use let?

Time:01-07

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();

CodePudding user response:

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.

CodePudding user response:

This really only comes down to whether or not you intend to store other information to $myDiv.

If not, then continue to use const. If yes, you should use let.

  •  Tags:  
  • Related