Why are literal objects declared with const in JavaScript currently?

Because of EcmaScript 6 I see examples that declare literal objects with the reserved word const.

Code example:

// Versão utilizada atualmente
const obj = {
   x: 'example'
};

// Versão utilizada anteriormente no EcmaScript 5
var obj = {
   x: 'example'
};

Basically, my doubts are as follows:

  • is this done to keep the object immutable?
  • is a protection to prevent the variable from being overwritten improperly by the programmer?
  • is a prevention of creating variables and functions with the same name by forgetting?

PS: the doubt is not about literal objects, but about this practice of using const to declare them.

Author: raphael, 2019-05-11

4 answers

In EcmaScript 6 var should no longer be used. Hence const or let are the modern options, and this is the only reason to no longer use var.

The recommendation is not written in the ES6 specification but is the reason why let and const were created. var is a way to declare variables with severe gaps and so it received strong substitutes (let and const) that cover the areas where var could be used, leaving it obsolete.

There is another full answer on this here: var, const or let? Which one to use?

Regarding your doubts:

Is this done to keep the object immutable?

No, it is to reference the immutable object. To make the object itself (and the reference) immutable you must use the Object.freeze():

const obj = Object.freeze({
   x: 'example'
});

Is it just a protection to prevent the variable from being overwritten?

Yes. But if the intention is power re-write the variable, then we should use the let

Is a prevention of creating variables and functions with the same name?

Yes.

 5
Author: Sergio, 2019-05-12 02:31:25

The Reserved WordCONST

The word const is a slightly misleading . Not defines a constant value, but a constant reference for a value.

Because of this, we cannot change constant primitive values, but we can change the properties of constant objects .

Primitive Values

If we assign a primitive value to a constant, we cannot change the primitive value

const PI = 3.141592653589793;
PI = 3.14;      // Isso dará um erro
PI = PI + 10;   // Isso também dará um erro

Constant Objects

You can change the properties of a constant object, since they can change. But you cannot reassign a constant object .

// Você pode criar um objeto const:
const car = {type:"Fiat", model:"500", color:"white"};

// Você pode alterar uma propriedade:
car.color = "red";

// Você pode adicionar uma propriedade:
car.owner = "Johnson";

const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"};    // ERROR

W3SCHOOLS-SOURCE

 4
Author: Comunidade, 2020-06-11 14:45:34

Because of EcmaScript 6 I see examples that declare literal objects with the reserved word const. This is done to keep the object immutable or is it just a protection to prevent the variable from being overwritten?

A: your answer is below according to MDN, follow the link:

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

Translated on Google!

This statement creates a constant whose scope can be global or local to the block in which it is declared. Global constants do not become properties of the object window, unlike variables var. An initializer for a constant is required; that is, you must specify its value in the same declaration in which it is declared (which makes sense, given that it cannot be changed later). the const statement creates a read-only reference for a value. This does not mean that the value that it contains is immutable, only that the identifier of the variable cannot be reassigned. For example, in the case where the content is an object, this means that the content of the object (for example, its properties) can be changed. All "temporal dead zone" considerations apply to let and const. A constant cannot share its name with a function or variable in the same scope.

 1
Author: , 2019-05-12 00:10:19

In fact, in ES6, you can declare the variables using let or const. As you said yourself, const is to create constants, that is, you declare once and will no longer reassign the value. In the case of let, you can reassign the value (common in loops, for example).

The main difference from let and const to var is scope. See the difference between the codes below:

for (var i = 0; i < 10; i++) {
  // faça alguma coisa
}

console.log('O valor de i é ', i);

// irá imprimir "O valor de i é 9"
for (let i = 0; i < 10; i++) {
  // faça alguma coisa
}

console.log('O valor de i é ', i);

// irá ocorrer o erro "ReferenceError: i is not defined", pois a variável i só existe dentro do bloco do for

In short, variables declared with let and const have the scope of block, while variables declared with var have only function scope, not block.

 0
Author: brunobastosg, 2019-05-11 16:16:38