The second way:
var CONSTANTE = 'soy una constante';
Do not create a constant but a variable
The only way to create constants in JavaScript ( ES 2015 ) is through keyword const
The difference between a constant and a variable is that the the reference can not be altered , that is, the operator =
can not be used to modify its value :
A constant (as its name implies) does not change its value during execution
For example:
var a = 1;
a = 2;
console.log(a); //Imprime 2, puesto que es una variable y su valor ha sido modificado
Instead:
const b = 3;
b = 4; // A diferencia de otros lenguajes esto no es error de sintaxis
console.log(b); // Sin embargo imprime 3 ya que el valor de 'b' no puede ser modificado.
It is important to note that this does not convert the object to which the constant refers to be immutable, that is, the value can be modified but not the reference.
For example:
const c = { nombre : "Juan", edad : 30 };
c.nombre = "Lucho";
console.log(c.nombre); // Imprime Lucho. c.nombre sí puede ser reasignado
However:
c = { nombre: "María", edad: "30"};
console.log(c.nombre); // Imprime Lucho. c no puede ser reasignado.
If instead you also want to make the immutable object you can use Object.freeze()
.
Example:
const d = Object.freeze({ nombre: "Pedro": edad: 25 });
d.nombre = "Juana"; // No es error de sintaxis pero no hace nada
console.log(d.nombre); // Imprime "Pedro", ya que el objeto d es inmutable
Object.freeze()
is not unique to constants, it can also be used in variables:
var e = Object.freeze({ nombre: "Rosa": edad: 28 });
e.nombre = "Jaime"; // No es error de sintaxis pero no hace nada
console.log(e.nombre); // Imprime "Rosa", ya que el objeto e es inmutable
However, since the variable e can not be a constant, it can be reassigned:
e = { nombre: "Tomás", edad: 23 };
console.log(e.nombre); // Imprime "Tomás", el objeto anterior sigue siendo inmutable y no
// ha sido modificado, simplemente ya no es referenciado por la
// variable e que ahora apunta al nuevo valor.
Another important thing to note is that although the operator =
can be used to "try" to reassign a constant (although this accomplishes nothing), trying to declare a constant again is a SyntaxError
const f = 5;
const f = 6; // Uncaught TypeError: Identifier 'f' has already been declared(…)