Const in JavaScript

testYourselfJavaScript JavaScript756 5 1

The const keyword was introduced with EcmaScript 2015 (ES6) together with let keyword.

There are few differences between const and let and const and var that's worth to know.

initialization

When we declare const we have to initialize it. If we don't do it we will get an error similar to below:

const MAX; // yntaxError: Missing initializer in const declaration

Redeclaration

The constant cannot be redeclared within the same function or block scope.

When we try to redeclare it we get an error similar to the below:

const a = 10;
const a = 5; // SyntaxError: Identifier 'a' has already been declared
var b = 2;
const b = 10; // SyntaxError: Identifier b' has already been declared
const c = 100;
var c = 50; // SyntaxError: Identifier 'c' has already been declared

Although the object/array created by const keyword cannot be redeclared, its properties/values are still modified.

const PERSON = {name: "John"};
PERSON.name = "Tom";
console.log(PERSON); // {name: "Tom"}
const ARR = [1,2,3];
ARR.push(4);
console.log(ARR); // [1,2,3,4]

Reassigning

The constant cannot be changed though re-assignment.

const MAX = 100;
MAX = 1000; //TypeError: Assignment to constant variable.

Temporal dead zone

A constant (const) cannot be accessed before it was declared. The constant is in a "temporal dead zone" from the start of the block until the declaration is processed.

console.log(MIN); // ReferenceError: MIN is not defined
const MIN = 5;

Scope

The const is limited in scope to the block, statement, or expression on which it is used. The main difference between const and var is that the local scope of a var variable is related only to the function.

const COMPANY = "Samsung";
if (COMPANY) {
    const COMPANY = "Sony";
    console.log(COMPANY); // Sony
}
console.log(COMPANY); // Samsung

Global property

At the top level of programs, const, unlike var, does not create a property on the global object.

var x = 10;
const y = 5;
console.log(this.x); // 10
console.log(window.x); // 10
console.log(this.y); // undefined
console.log(window.y); // undefined