Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should objects be declared const or let? [closed]

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?

like image 840
redOctober13 Avatar asked Oct 03 '17 20:10

redOctober13


People also ask

Should object be const or let?

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.

Should I use const or let in for loop?

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.

Are let and const variable closed over?

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.

Is const or let faster?

Clearly, performance-wise on Chrome, let on the global scope is slowest, while let inside a block is fastest, and so is const.


1 Answers

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

like image 182
LennieCodes Avatar answered Sep 29 '22 05:09

LennieCodes