JavaScript Const - How to use 'const' keyword in JavaScript



JavaScript Assignment Operators

  • The const keyword was introduced in ES6 (2015).
  • Variables defined with const cannot be Redeclared.
  • Variables defined with const cannot be Reassigned.
  • Variables defined with const have Block Scope.

Cannot be Reassigned

  • A const variable cannot be reassigned.
javascript-const

Sample Code

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript const</h2>

<p id="demo"></p>

<script>
try {
  const PI = 3.141592653589793;
  PI = 3.14;
}
catch (err) {
  document.getElementById("demo").innerHTML = err;
}
</script>

</body>
</html>

Output

JavaScript const
TypeError: Assignment to constant variable
    

Correct

  • const PI = 3.14159265359;

Incorrect

  • const PI;
  • PI = 3.14159265359;

When to use JavaScript const ?

Always declare a variable with const when you know that the value should not be changed.

  • Use const when you declare.
    • A new Array
    • A new Object
    • A new Function
    • A new RegExp

Constant Arrays

  • You can change the elements of a constant array:
// You can create a constant array:
const cars = ["kaashiv", "infotech", "welcome"];

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

// You can add an element:
cars.push("arrays");
But you can NOT reassign the array:
const cars = ["kaashiv", "infotech", "welcome"];

cars = ["venkat", "praveen", "soumith"]; // ERROR

Related Searches to JavaScript Const - How to use 'const' keyword in JavaScript