JavaScript Const

The JavaScript const variable is also used to declare a variable like var. But we cannot redeclare const in the whole program. The const keyword was introduced in ES6.

The JavaScript const variables should be assigned the value at the time of declaration.

The JavaScript const should be used when we declare

  • new Object
  • new Regular Expression
  • new Array
  • new Function

There is a little misleading concept in the const keyword because it is not used to define constant value. It is used to define a constant reference to a value.

Because of this, we cannot reassign:

  • constant value
  • constant array
  • constant object

But we can change:

  • constant array elements
  • constant object properties

Constant Arrays

The constant array properties can be changed:

But reassigning the arrays is not allowed:

Constant Objects

The constant object properties can be changed:

But reassigning the objects is not allowed:

JavaScript Const – Block Scope

The block scope for the declaration of a variable with const is similar to the let keyword.

JavaScript Const – Hoisting

The variables we defined with the const keyword can be hoisted to the top of the block but we cannot initialize these variables. It means that using the const variable before its declaration will cause a ReferenceError:

Browser Support

The internet explorer 1o or earlier browsers do not fully support the const keyword. The list of supported browser versions is defined below:

JavaScript Const