ConstAndYa

Omar Gonzalez
4 min readApr 24, 2021

This article will also discuss let, but since that particular JavaScript variable declaration keyword was featured in the title of my last article, const gets top billing this time. Each of them stands head and shoulders over var in terms of reducing the level of potential for bugs; and each provides its own level of permanence.

Block-scoped rather than function-scoped, variables declared with let or const don’t suffer from the wanderlust that is inherent to var spawn. And, also unlike a var variable, which can be declared multiple times, let and const variables can only be declared once. Take a look.

The double-declaration of georgeSurname with var is perfectly tolerated; Not only am I permitted to finish building the function, but the function is permitted to work, whereas when I try the same thing with let or const, an error message pops up the moment that I hit the return key. Just as var function-scoping can make bugs much more difficult to find, the JS engine’s refusal to reign in such double declarations variables can be equally counter-productive.

But one useful similarity that let variables share with their var predecessors is that each can be assigned a different value than the one with which it’s originally endowed.

This can come in very handy for something like an index number that increases for each element when looping through an array.

But sometimes we need a variable’s value to be immutable; and that’s what const is for. Once a const variable is assigned a value, that’s all she wrote; it keeps that value forever.

Now it’s important to bear in mind this holds true even when a variable is assigned to an object. When declared with const, and assigned a value of, say, an array, a variable will always point to that array, BUT the contents of that array are subject to change.

And there’s one more difference between const and let. Similar to var, let can be used to declare a variable without that variable immediately being assigned a value.

That won’t fly with const.

And that’s because of the permanent nature of const; it doesn’t permit reassignment after initialization. So any variable declared with const must simultaneously be assigned a value.

Also, a word of advice. Even though it’s considered a best practice to use const whenever the variable’s value doesn’t need to be mutable, my experience has been that when experimenting with JS code in the Developer Tools console, one is usually better off using let, or else one needs to refresh the page every time one wants to try something new with the value of the variable. But with that one exception, I agree that it’s best to use const whenever feasible, and that let should always be used instead of var when it’s not feasible to use const.

SOURCE:

--

--