I'm not asking what's technically possible; I know you can do
const a = [];
const b = {};
a.push['sup'];
b.test = 'earth';
What I'm wondering is whether there's any convention for preferring let
over const
when it comes to arrays and objects that will have their internals modified. If you see an object declared with const
, do you assume the intention was for the object to be immutable, and would you have preferred to see let
instead, or, since some linters (like tslint) have a problem with that, is it better just to declare it with const
and trust that anyone else reading the code knows that that doesn't mean it's immutable?
Summary. As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable.
A for loop's control variable is normally not constant (since in the normal case you update it in the "update" clause of the for ; if you don't, for may be the wrong loop to use), so you normally use let with it. Save this answer.
Hoisting of const var declarations are globally scoped or function scoped while let and const are block scoped. var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.
Clearly, performance-wise on Chrome, let on the global scope is slowest, while let inside a block is fastest, and so is const.
The const
keyword in front of an object implies that there is an object, and you're working with references to alter it. It also (correctly) implies that you should not attempt to reassign references to this object.
const obj = {a: 'foo', b: 'bar'};
const obj2 = {z: 'baz'};
obj = obj2; // const will prevent this operation.
const
does not imply that the object properties should not be altered. It does imply that you should not try to change the reference.
If you plan to reassign references to the object, then you use let
.
Source: AirBnB Javascript Style Guide
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