Skip to content

JavaScript const variable | Code

  • by

You can define a const variable using the const keyword in JavaScript. In the same way, you declare variables with let and var.

const var_name= value;

The value of a constant can’t be changed through reassignment (i.e. by using the assignment operator), has Block Scope and it can’t be redeclared.

Note: JavaScript const variables must be assigned a value when they are declared:

JavaScript const variable

Simple example code variables cannot be reassigned.

<!DOCTYPE html>

    const PI = 300;
    PI = 3.14;     
    PI = PI + 10; 




JavaScript const variable

Const variable cannot be hoisted

   x = 100;  
   const x;     //Syntax Error  

const variable cannot be initialized after the declaration

   const x;  
   x = 100;    //Syntax Error  

Block scope

if (MY_FAV === 7) {
  // this is fine and creates a block scoped MY_FAV variable
  // (works equally well with let to declare a block scoped non const variable)
  let MY_FAV = 20;

  // MY_FAV is now 20
  console.log('my favorite number is ' + MY_FAV);

  // this gets hoisted into the global context and throws an error
  var MY_FAV = 20;

// MY_FAV is still 7
console.log('my favorite number is ' + MY_FAV);

It’s good practice to use const for values that shouldn’t be reassigned, as it can help prevent accidental reassignments and make your code more robust. However, it’s important to note that const does not make objects or arrays immutable. If you need immutability, you may need to use other techniques, such as the Object.freeze() method for objects or using immutable data structures.

Comment if you have any doubts or suggestions on this JS const topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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