Introduction
Namaste, In this blog I will discuss the below topics.
What is the 'const' keyword?
Using the 'const' keyword
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
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
Cannot be re-declared
const myval = "Hari"; //const myval =12; // error - cannot be re-declared
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();
It is not hoisted i.e. it can only be accessed after initialization
// not hoisted //console.log("myval3", myval3); // error const myval3=12;
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