Skip to content

JavaScript const keyword | Basics

  • by

The JavaScript const keyword is used to define a new variable. Use it when you do not want to change the value of that variable for the whole program.

const varName = value;  

A normal variable value can be changed but const variable values can’t be changed. You don’t have to use var or let keyword while using the const keyword.

JavaScript const example

A simple example code const variable can’t be reassigned.

<!DOCTYPE html>
<html>
<body>
  <script>
    const number = 100;

    try {
      number = 99;
    } catch (err) {
      console.log(err);

    }

    console.log(number);

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

Output:

JavaScript const keyword

You can change the elements of a constant array by an index value.

const cars = ["A", "B", "C"];

// You can change an element:
cars[0] = "X";

// You can add an element:
cars.push("Y");

But you can NOT reassign the array:

<script>

    const cars = ["A", "B", "C"];
    cars = ["X", "Y", "Z"]; // Uncaught TypeError: invalid assignment to const ‘cars’

</script>

Same with constant Objects, You can change the properties of a constant object but can’t reassign the object:

Where to use JavaScript const?

Answer: Anytime you can declare a variable with const unless you know that the value will change. You use it with:-

  • A new Array
  • A new Object
  • A new Function
  • A new RegExp

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 *