A Simple Explanation of JavaScript Variables: const

Variables declared with the const maintain constant values. const declarations share some similarities with let declarations. The const keyword has all the properties that are the same as the let keyword, except the user cannot update it.

const  x =1;
console.log(x);      //  Output : 1        

Variables defined with const cannot be redeclared.

const x = "John";
const x = 0;

// Error: Identifier 'x' has already been declared        
const is block scoped

A block is a chunk of code bounded by {}. A block lives in curly braces. Anything within curly braces is a block.

So a variable declared in a block with let is only available for use within that block.

const str = 5;

if (str > 2) {
    const hello = "Hello World";
    console.log(hello);     //  Output : "Hello World"

console.log(hello)          // Output : hello is not defined        

We see that using hello outside its block (the curly braces where it was defined) returns an error. This is because let variables are block-scoped.we can see another example below

const x = 10;
console.log(x);        // Output : 10
const x = 2;
console.log(x);        // Output : 2

console.log(x);        // Output :10        

 const cannot be updated or re-declared

const message = "Hello World";
message = "How Are you";      // Error: Assignment to constant variable. 

It gives error because we cannot update variable which is defined by const.

const greeting = "Hello World";
const greeting = "How Are you";    
// Error: Identifier 'greeting' has already been declared        

This gives an error because we cannot reassign the value to same variable.

Posted in

Ankit Patel

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top