JavaScript - The 'const' keyword

Introduction

Namaste, In this blog I will discuss the below topics.

  1. What is the 'const' keyword?

  2. Using the 'const' keyword

  3. Complete source code

What is the 'const' keyword?

The variables declared using 'const' keyword cannot be changed i.e. once declared they are not updatable.

Using the 'const' keyword

Below are various scenarios of using the 'const' keyword

  1. The variable cannot be updated after the declaration

    
     const myval=10;
     console.log("type", typeof myval, " value", myval);
     // result : type number  value 10
     //myval = "ram"; //error
    
  2. Cannot be re-declared

     const myval = "Hari";
     //const myval =12; // error - cannot be re-declared
    
  3. Has block scope i.e. it cannot be accessed outside a code block

     // Has block scope
     if (myval > 6) {
         const myval2=11;
     }
     //console.log("type", typeof myval2, " value", myval2); // error
    
     //block scope in function
     function fx() {
         if (myval > 6) {
             const myval4=8;        
         }
         //console.log("myval 4", myval4); //error
     }
     fx();
    
  4. It is not hoisted i.e. it can only be accessed after initialization

     // not hoisted
     //console.log("myval3", myval3); // error
     const myval3=12;
    
  5. The object declared is also constant but the elements inside it are updatable

     const obj = {
         no:10,
         name: "Ram"
     };
     //obj = 100; // error
     obj.no = 200; // no-error , works
    

Complete Source Code

//Objective: Using the const keyword
//Author: Mahavir DS Rathore

const myval=10;
console.log("type", typeof myval, " value", myval);
// result : type number  value 10
//myval = "ram"; //error

//const myval =12; // error - cannot be re-declared 

// Has block scope
if (myval > 6) {
    const myval2=11;
}
//console.log("type", typeof myval2, " value", myval2); // error

// not hoisted
//console.log("myval3", myval3); // error
const myval3=12;

//block scope in function
function fx() {
    if (myval > 6) {
        const myval4=8;        
    }
    //console.log("myval 4", myval4); //error
}
fx();

const obj = {
    no:10,
    name: "Ram"
};

//obj = 100; // error
obj.no = 200; // no-error , works

Did you find this article valuable?

Support Programming with Mahavir by becoming a sponsor. Any amount is appreciated!