How to create constants in JavaScript? Explain with examples.

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code to create constants in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h1>Const example</h1>
<button class="Btn">CLICK HERE</button>
<p class="sample"></p>
<h3>Click the above button to try changing const value</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   const a = 33;
   sampleEle.innerHTML = "a = " + a + "<br>";
   document.querySelector(".Btn").addEventListener("click", () => {
      try {
         a = 44;
      }
      catch (err) {
         sampleEle.innerHTML += "Error : " + err;
      }
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button to change constant value −

raja
Published on 16-Jul-2020 06:47:45
Advertisements