Const in Javascript | Scope, Example

Const in Javascript is another keyword introduced in ES6 that is used to declare a read-only variable, meaning, a variable whose value cannot be reassigned.

In other simple words, if a variable is defined with a const keyword, its value cannot be changed (or modified) afterward throughout its lifetime.

Javascript const keyword allows us to define a constant value. It must be initialized when the variable is declared.

If a value of the variable assigned with a const keyword is modified, TypeError will be thrown.

For example, consider the following code below:

const firstName = "Ivaan"; // Defining a constant.
firstName = "Herry"; // throws read-only exception.

Here, we have declared as a variable named firstName, and indicated that it cannot be changed by using the const keyword.

Attempting to compile this code, will generate an error saying that firstName is read-only property because, in the second line of code, we are trying to modify the value of firstName to the string “Herry”.

It is important to note that a constant can never be declared without assigning a value. Attempting to declare a constant without assigning it, will produce a SyntaxError.

For example, consider the below code:

const x; // raises a SyntaxError.
const x = 10; // works as expected.

Why need Const Keyword in Javascript?


Before ES6, developers usually declare a variable with var keyword that was supported to be constant. For example, consider the following code:

var const_pi = 3.14;
var r = 10;
document.write(const_pi * r * r); // output: 314.

The value of pi should always be constant. In the above code, there is still a chance that might accidentally change its value somewhere in the program.

There is no native protection to the value of pi. Therefore, the const keyword was introduced in ES6 to provide native protection to the constant variables.

So, the preceding code should be written in this way in ES6:

const pi = 3.141;
var r = 10;
document.write(pi * r * r); // output: 314.
pi = 4; // throws read-only exception.

In the last line of code, we have tried to change the value of pi, a read-only exception has been thrown.

Scope of Const keyword in Javascript


Variables declared with a const keyword are blocked-scope variables. Constant variables follow the same scoping rules as variables that are declared with the let keyword.

Let’s take an example program in which we will see the scope of constant variables.

Program code 1:

<html>
<body>
<script>
    const x = 20; // accessible globally.
    function myFunction()
    {
        document.write("Value of x: " +x+ "<br>");
        const y = 30; // accessible throughout function.
        if(true)
       {
         const z = 40; // accessible throughout the "if" statement.
         document.write("Value of y: " +y+ "<br>");
        }
      document.write(z);
   }
   myFunction();
</script>
</body>
</html>
Output of code:
            20
            30
            ReferenceError Exception

As you can observe in the above code snippet, variables declared with const keyword are behaving the same way as block-scoped variables, when they come to the scoping rule.

Thus, the const keyword has the same scoping and variable hoisting rules as the let keyword. Variables declared with const keyword have block scoping and do not get hoisted at the top of the scope.

For example, consider the following code snippet below:

Program code 2:

<html>
<body>
<script>
   function myFunction()
   {
     document.write("Variable declared with const keyword is not hoisted");
// Referenced before declaration.
     document.write(x);
      const x = 20; // ReferenceError because x is not defined.
   }
   myFunction();
</script>
</body>
</html>
Output of code:
        Variable declared with const keyword is not hoisted
        ReferenceError Exception

The key difference between let and const keywords is that variables declared with let keyword can be reassigned a new value whereas, variables declared with const keyword can never be reassigned a new value (i.e. it is immutable).

Referencing Objects using Constant Variables in Javascript


A variable marked with const keyword creates a read-only reference to a value. It does not mean that the value held by a reference is immutable.

When we assign an object or an array to a variable, the reference of the object is constant to that variable and not to the object itself.

Therefore, the contents of an array or object properties are mutable but the reference of object or an array is immutable. Let’s take an example program based on these concepts.

Program code 3:

<html>
<body>
<script>
   const x = {
       name1 : "John",
       name2 : "Deep",
       name3 : "Ivaan"
   };
   document.write(x.name1+ "<br>");
   document.write(x.name2+ "<br>");
   document.write(x.name3+ "<br>");
    
// Reassigned of variable. 
    x = "Herry"; // throws read-only exception.
    document.write(x);
</script>
</body>
</html>
Output of code:
          John
          Deep
          Ivaan
          x is read only : Exception

In this example program, x variable stores the address (i.e. reference) of the object. Therefore, the address of the object is a value of x variable and it cannot be changed.

But, here the object is mutable. When we attempted to assign another object to variable x, we got an exception because we are attempting to change the value of variable x.


4. Let’s take a simple example where we will find the area and circumference of a circle and see the output. Look at the snippet code below.

Program code 4:

<html>
<body>
<script>
    const pi = 3.14;
    const r = 10;
    function calArea()
   {
      let area = pi * r * r;
      document.write("Area of circle: " +area+ "<br>");
    }
   function calCircumference()
  {
     let circum = 2 * pi * r;
     document.write("Circumference of circle: " +circum);
   }
    calArea();
    calCircumference();
</script>
</body>
</html>
Output of code:
          Area of circle: 314
          Circumference of circle: 62.80

When to use Const or Let in Javascript?


While writing the code in ES6, always use const keyword to declare variables whose values will not change.

Use let keyword only when you need to perform any changes (reassignments) to the variable and completely avoid using var keyword.

Common Examples based on Const Keyword


Here, we have collected some common examples based on the const keyword that should be practiced. Look at the following code snippet.

1. const x; // SyntaxError: Missing initializer in const declaration.
2. const x = 10;
    document.write(x); // output: 10
    x = 20; // TypeError: Assignment to a constant variable.

3. if(true) {
      const name = "John";
    }
   document.write(name); // ReferenceError: name is not defined.

4. if(while) {
        const x = 20;
    }
    document.write(x); // ReferenceError: x is not defined.

5. function showMe(){
       const scName = "RSVM";
    }
     document.write(scName); // ReferenceError: scName is not defined.
6. const x = {
       a : 10,
       b : 20;
   };
   x = { a : 30, b : 40}; // It will not work.
   x.a = 60; // It will work because only a property of object x has been changed.

7. const x = 10;
    let y = x; // output: x = 10, y = 10
    y = 20; // output: x = 10, y = 20

In code example 7, x referenced a primitive number 10. Then, we assigned y to the same value as x. In this case, x and y both have the same value 10. We then reassigned the value of 20 to y, but still, x has a value of 10.


8. If we assign a non-primitive value to a variable, it is done by reference. Therefore, if any changes happen, they will subsequently affect all references to that object. Look at the following code snippet below:

 const p = { value : 10};
 let q = p; // output: p.value = 10, q.value = 10;
 q.value = 20; // output: p.value = 20, q.value = 20;

In the above code example, the change to the value property of q also occurs in the value property p changing as well because variables p and q are both referencing the same object. So, any changes to one of them will also influence the other.


9. Redeclaration of an existing var variable to const is not allowed in the same scope. Look at the below example.

var x = 20; // allowed
const x = 30; // not allowed

10. Redeclaration of an existing let variable to const is not allowed in the same scope. See the below example.

let p = 20; // allowed
const p = 30; // not allowed

11. Reassigning an existing const variable is not allowed in the same scope. For example:

const a = 10; // allowed
var a = 20; // not allowed
let a = 30; // not allowed
const a = 50; // not allowed

12. Redeclaring a variable with const keyword is allowed in another block scope or another block. Look at the examples below:

const firstName = "Deep"; // valid
{
    const firstName = "Herry"; // valid
}
{
    const firstName = "Ricky"; // valid
}

Hope that this tutorial has covered almost all the important points related to const keyword in Javascript with example program. I hope that you will have understood the basic concepts of Javascript const keyword.
Thanks for reading!!!