Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Variable 'X' can be made constant", what does 'constant' mean?

VStudio or ReSharper is giving me the suggestion below:

enter image description here

What does constant mean in this scenario? If it's a constant in the current method scope, what's the purpose? Methods tend to be small and therefore it shouldn't give any advantage compared to be a regular var?

Please enligten me

like image 767
jgauffin Avatar asked Feb 09 '23 22:02

jgauffin


1 Answers

It's nothing complicated.

It's typically better to use const over let (and definitely var), since const makes it easier to understand code, since you only have to look at the initial assignment to know what the contents of the variable are. Use it as much as possible.

It should be noted that though constants can not be reassigned, in some cases their contents can, for example when dealing with an array or object. For example, const x = [1]; x[0] = 2; is perfectly valid code, but this should be considered an anti-pattern, because one would expect a constant to remain constant, thus breaking the principle of least astonishment.

You can of course update an array with a const by simply creating a copy of the array and assigning it to a new const:

const x = [1];
const x2 = [...x, 2];

This does have performance considerations you might need to consider when dealing with extremely large arrays.

The const and let keywords are part of the ECMAScript 2015 standard. So when using const or let and transpiling down to older ECMAScript targets const and let are transpiled to the old var. Nowadays all browsers support const and there are no real performance considerations for using one or the other.

like image 90
Lodewijk Bogaards Avatar answered Feb 12 '23 12:02

Lodewijk Bogaards