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), have 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 variable cannot be reassigned.

<!DOCTYPE html>
<html>
<body>
  <script>

    const PI = 300;
   try{
    PI = 3.14;     
    PI = PI + 10; 
  }catch(error){
    console.log(error)

  }
  console.log(PI)

</script>
</body>
</html>

Output:

JavaScript const variable

Const variable cannot be hoisted

<script>  
   x = 100;  
   document.write(x);  
   const x;     //Syntax Error  
</script>  

const variable cannot be initialized after declaration

<script>  
   const x;  
   x = 100;    //Syntax Error  
   document.write(x);  
</script>  

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);

Do 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 *