Is it neccessarry to store jQuery objects as constant?


Instead of ;
const navDropdown = (’#nav-dropdown’);

Can we use ;
var navDropdown = (’#nav-dropdown’);

If yes, what is the benefit of storing the object as const?

PS: I tried it and it was running fine with var in place of const


The only thing that is necessary is that our variables are locally scoped. We can use, const, let or var for this purpose. Which we use is inconsequential.

const prevents variables from being reassigned. If they are primitive values, like a number or string, etc. Their values are fixed and cannot be altered. If they are an array or object then the data type is fixed but we can still manipulate the values and items.

Above, navDropdown is (or rather should be) assigned a jQuery object.

const $navDropdown = $('#nav-dropdown');

There is no chance that this will be changed during the session since it is a cached element node which will not change. Mind, dynamically more child nodes could be added by the program, but that won’t change the identity of the cached node itself. const just prevents our program from reassigning the variable a new node.

1 Like