What is the difference in the declaration of variables using const? [duplicate]

-3

In the were added some functionalities, among them is the const that is apparently used in the same way as var , to declare variables.

What is the difference between declared variables using this const or not?

    
asked by anonymous 19.12.2017 / 17:31

1 answer

0

Well, fundamentally speaking, const serves not only to define that the variable has the global scope, but mainly to make the value of the variable immutable, so that it can not be changed and because of this, to have a constant value .

Explanations

Modifier const

As some people already know from other languages, const refers to the word constante which means immutable or always the same. The scope of const in question is a global scope, just as if there were no let nor var . So the reason for this modifier is not for scoping purposes, but because of the fact that a variable declared as const becomes immutable, resulting in an error any attempt to assign to it. However there are two exceptions, if the value of the const variable is an object, you can still change the value of the attributes of that object, but the object remains immutable, you can not assign another object to it. Also suitable for Array's, you can add more elements to the Array assigned to it, but can not assign another Array to it.

Example

VARIAVEL_GLOBAL_COMUM = 0;
const MINHA_CONSTANTE = 1;

MINHA_CONSTANTE = 2; //Isso resulta em um erro. Você não pode alterar o valor de uma constante.
VARIAVEL_GLOBAL_COMUM = 3; //OK.

var MINHA_CONSTANTE = 4; //Resulta em erro porque você não pode utilizar o mesmo nome reservado para uma constante definida.
let MINHA_CONSTANTE = 4; //Resulta em erro porque você não pode utilizar o mesmo nome reservado para uma constante definida.

const OBJETO_CONSTANTE = { atributo: 'texto' };

OBJETO_CONSTANTE = { outroAtributo: 'texto' }; //Resulta em erro. Você não pode atribuir outro objeto para a constante já definida.
OBJETO_CONSTANTE.atributo = 'Outro Texto'; //Funciona. Porque você pode alterar o valor do atribuito dentro do objeto já atribuido.

const ARRAY_CONSTANTE = [1,2];

ARRAY_CONSTANTE = [1,2,3]; //Erro. Você não pode atribuir outro Array para o array constante já definido.
ARRAY_CONSTANTE.push(3); //Funciona. Você pode adicionar um valor no Array já atribuido na constante.

Note that the const modifier is not used for different scope purposes, but for variable freezing, but given that it is possible to receive an Object that can have the value of its attributes changed and an Array that can have more elements added.

Conclusion

The const has a global scope, as well as declaring a variable without a modifier, but its main function is to make variables immutable.

Sources / References:

19.12.2017 / 17:31