VStudio or ReSharper is giving me the suggestion below:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With