ES6 - The const keyword

es6

// ECMAScript 6 - The const keyword:

With ECMAScript 6, we can define constants using the const keyword.  Variables 
(also known as bindings) declared using the const keyword are considered as 
constants, meaning their values cannot be changed after set.  For this reason, 
every const binding must be initialized on declaration:

const maxItems = 30;

Constants, declared using the const keyword, like let declaration, are block-
level declarations.  They are not accessible when the execution flows out of the 
block in which they were declared, and const declarations are not hoisted.  For 
example:

if (condition) {
  const maxItems = 5;
  ...
}

// maxItems is not accessible.

In the above code, the constant maxItems is declared within an if block.  After 
the if block finishes executing, maxItems is not accessible outside that block.

In another similarity to let, a const declaration throws an error when made 
with an identifier for an already defined variable in the same scope.  It does 
not matter whether that variable was declared using var or let.  For example:

var message = "Hello";
let age = 25;
const message = "Goodbye!"; // throws an error
const age = 30; // throws an error.

The two const declarations would be valid, but given the previous var and let 
declarations, the two const declarations results in syntax errors.

Attempting to assign a const to a previously defined constant will throw an 
error in both strict and non-strict modes:

const maxItems = 5;
maxItems = 6; // throws an error

Much like constants in other languages, we cannot assign a new value to a 
constant after declaration.  However, unlike constants in other language, the 
value that a constant holds can be modified if it is an object.  A const 
declaration prevents modification of the binding, not the value.  That means 
that const declaration for objects do not prevent modification of those objects.  
For example:

const person = {
  name: "Nicholas"
};

person.name = "Greg"; // works

person = {
  name: "Greg"
};  // throws an error.

In the above code, the binding person is created with an initial value of an 
object with one property.  It is possible to change person.name without causing 
an error because this changes what person contains but does not change the 
value that person is bound to.  When this code attempts to assign a value 
to person, thus attempting to change the binding, an error will be thrown.

In other words, for simple values, the const declarations works as expected.  It 
also works as expected for objects, but it does not prevent us from changing 
attributes / properties of the object.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License