Why are literal objects declared with const in Javascript currently?

Asked

Viewed 711 times

8

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::

  • This is done to keep the object unchanging?
  • It is a protection to prevent the variable from being overwritten improperly by the programmer?
  • It is a prevention of the creation of variables and functions with the same name by forgetfulness?

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

  • 3

    Just for the record const nay makes the object immutable. For this, you must use the Object.freeze.

  • Complementing the previous comment... const makes the variable immutable, but what the variable has is not the object itself, but its reference

  • 2

    Related: https://answall.com/a/206121/112052

4 answers

5


In Ecmascript 6 the var. Hence the const or the let are the modern options, and that is the only reason not to use more the 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 serious gaps and so received strong substitutes (let and const) which cover the areas where var could be using, leaving it obsolete.

There’s another complete answer to that here: var, const or Let? Which to use?

In regards to your doubts:

This is done to keep the object unchanging?

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

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

It is only a protection to prevent the variable from being overwritten?

Yes. But if the intention is to be able to rewrite the variable, then we should use the let

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

Yes.

4

The Reserved Word CONST

The word const is a misleading. NAY defines a constant value rather a constant reference for a value.

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

Primitive Values

If we assign a primitive value at a constant, we cannot alter the primitive value

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

Objetos Constants

You can change the properties of a constant object, for they can change. But you CANNOT reallocate 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

1

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 only a protection to prevent the variable from being superscript?

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

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

Translated into Google!

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

  • 1

    From what I understood this practice aims to protect from variables and functions with the same name and also avoid overwriting the value improperly.

  • @rcs In theory yes but do not always trust this, in fact the protection is the set of logic of your system... as was said above "The const statement creates a read-only reference for a value" but we are not 100% sure if your goal is this, an example is the browsers and versions... this year security was detected some browsers, type Chrome v71, normal, we are in constant evolution, security is an important factor today in the era of artificial intelligence.

  • My comment was not about web security, but about protecting against eventual failures of the programmer himself to overwrite values for lack of attention and redeclare variables by forgetfulness.

  • @rcs positive, very correct.

0

Actually, in ES6, you can declare variables using let or const. Like you said yourself, const is to create constants, ie 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 of let and const to the var is the 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 block scope, while variables declared with var only have function scope, not block.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.