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?
const
for this purpose, because the variable will always refer to the same object. But if it's your code, use whatever you prefer. If you work in a team and are worried they might get confused then write a coding standards document for the team: problem solved. – Journeymanconst
if possible. If you really need to freeze the object, use developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. – Bouillabaissevar
, still the preferred way to declare a variable that doesn't need special scoping rules or immutable behaviour – Kevenvar
anymore. There's really no reason to. As for which to use,let
orconst
, that's all up to opinion. If I intend for something to not be touched, I useconst
. If it really shouldn't be touched, and it's some kind of object, I useObject.freeze
. – Corianderconst
, since you’re most likely not going to redefinea
andb
. I personally know that it doesn’t mean that they are immutable; for immutability I would use e.g.Object.freeze
, but someone else might misinterpret that… – Battleaxvar
all the time, and only use the other two when they make things easier. If you never find a reason to use variables that aren't block scoped, that's up to you, I do. – Kevenvar
just uses function scoping rather than block scoping. If I intend to use a variable through a function then I declare it at the function scope withlet
orconst
. Declaring variables in child blocks which are then used in parent or siblings blocks is confusing and uncomfortable in my opinion. – Coriander