JavaScript const Keyword | const Variable

The JavaScript const keyword is used to create a block-scoped constant variable, whose value can not be changed/updated. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      const x = 10;
      document.getElementById("xyz").innerHTML = x;
   </script>
   
</body>
</html>
Output

Note - The const variable can neither be updated nor be re-declared.

The const variable can be used as a constant in a program. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="abc"></p>
   
   <script>
      const PI = 3.14159;
      var radius = 12.8;
      var area = PI * (radius*radius);
      document.getElementById("abc").innerHTML = area;
   </script>
   
</body>
</html>
Output

Also, use const variable, if the value of variable should not change further in the program. You can use const, when you need to declare a new array, object, function, or a RegExp.

Note - If you will use const to declare an array, then let me tell you. You can change the elements, but can not re-assign the array. Same goes with const object. That is, you can change the properties, but can not re-assign the object.

JavaScript Online Test


« Previous Tutorial Next Tutorial »