View video tutorial

JAVASCRIPT const

JAVASCRIPT

Using the const keyword, JavaScript can create a fixed value called a constant, the value of the constant always remains the same.

JavaScript Constant variables


➔ JavaScript uses constant references for immutable data or fixed values, so no changes are allowed to it.

➔ Constant reference ensures that the value behaves like a read-only variable and no assignment is allowed.

Key features of const in JavaScript:


No Reassignment

➔ Constant type data only takes its value at initialization time. A variable of constant type cannot be changed during application runtime and doing so will result in a TypeError.

Syntax

const name = "David";
name = "Brown"; // Error: Assignment to constant variable.
JavaScript const reassignment error

Example

<!DOCTYPE html>
<html>
<head>
        <title>JavaScript const example</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="utf-8">
</head>
<body>
        <h3>JavaScript const example</h3>
        <p id="demo"></p>
        <script>
                /*  TypeError: Assignment to constant variable. */
                try {
                        const name = "David";
                        name = "Brown";
                } catch (err) {
                        document.getElementById("demo").textContent = err;
                }
        </script>
</body>
</html>
Try it Now »

Click on "Try it Now" button and see how the code works.


Must be initialized

➔ A constant cannot be in an undefined state, so the developer must ensure that the constant has a value assigned.

➔ If a constant is mistakenly not assigned an initial value, an error such as SyntaxError will occur. So the developer must be aware of doing constant initialization.

Syntax

const name; // Error: Missing initializer in const declaration.
JavaScript const initialization error

Example

<!DOCTYPE html>
<html>
<head>
        <title>JavaScript const example</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="utf-8">
</head>
<body>
        <h3>JavaScript const example</h3>
        <p id="demo"></p>
        <script>
                /*  SyntaxError: Missing initializer in const declaration */
                /*  Check console in developer tools to see syntax errors*/
                try {
                        const name;
                } catch (err) {
                        document.getElementById("demo").textContent = err;
                }
        </script>
</body>
</html>
Try it Now »

Click on "Try it Now" button and see how the code works.


Block scoping

➔ Like the let keyword, the const keyword is limited to the block {} in which it is declared, meaning it is not accessible outside that block.

Sample code

if (true) {
  const x = 5;
  console.log(x); // Output: 5
}
// const 'x' is visible inside the if-block
console.log(x); // ReferenceError: x is not defined outsite the if-block

Shadowing of constants in different scopes.

➔ A constant can be declared with the same name but in different blocks without any conflict. This is called the shadowing of the constant.

Sample code

const x = 15; // Global scope or outer scope.
if (true) {
  const x = 5; // const declared in the local block scope.
  console.log(x); // Output: 5
}
console.log(x); // Output: 15 //the outer constant value remains unchanged.

Const hoisting in JavaScript

➔ In JavaScript, const is hoisted, but it enters a temporal dead zone. This means that it cannot be used before the line in which it is declared.

Sample code

// Temporal Dead Zone (TDZ) for 'myconst' begins here
console.log(myconst); // ReferenceError: variable exists but cannot be accessed 'myconst' before initialization

const myconst = 1234; 
// TDZ ends here
console.log(myconst); // Output: 1234

Reference Binding (Immutable Binding)

➔ For any constant of type JavaScript Object or JavaScript Array, JavaScript binds a constant reference (immutable binding) with the object itself. So new assignments are not possible but the object's properties or array values ​​can be changed without any problems.

➔ Remember: Constants of primitive types (e.g. number, string, boolean) are inherently immutable, so the value cannot be changed. However, object properties and array values ​​can still be changed.

For object

const student = { name: "James", age: 20 };
student.name = "John"; // object's property can change.
student.age = 22;      // object's property can change.

student = { name: "Olivia", age: 18 }; // Error: Assignment to constant variable reference
For array

const demoarr = [1,2,3,4];
demoarr[2]= 4 // array's element can change.
demoarr[3] = 8;      // array's element can change.

demoarr = [20,30,50]; // Error: Assignment to constant type variable reference
JavaScript const object/array

Example

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript const object/array example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
</head>
<body>
    <h3>JavaScript const object/array example</h3>
    <p id="demo"></p>
    <script>
        /*  TypeError: Assignment to constant variable. */
        /*  Check console in developer tools to see syntax errors*/
        try {
            const student = { name: "James", age: 20 };
            student.name = "John"; // object's property can change.
            student.age = 22;      // object's property can change.
            student = { name: "Olivia", age: 18 }; // Error: Assignment to constant variable reference

            const demoarr = [1, 2, 3, 4];
            demoarr[2] = 4 // array's element can change.
            demoarr[3] = 8;      // array's element can change.
            demoarr = [10, 20, 30]; // Error: Assignment to constant variable reference
        } catch (err) {
            document.getElementById("demo").textContent = err;
        }
    </script>
</body>
</html>
Try it Now »

Click on "Try it Now" button and see how the code works.


let vs const keywords for declaration in JavaScript


Keyword Scope Reassignment Redeclaration Description
let Block-scoped Allowed Not allowed The standard and recommended way to declare a variable whose value may change.
const Block-scoped Not allowed Not allowed The standard and recommended way to declare a constant type variable whose value cannot be changed after initialisation.