Computer >> Computer tutorials >  >> Programming >> Javascript

Various ways to define a variable in JavaScript


There are three ways to define a variable in JavaScript −

  • let − The JavaScript Let keyword introduced in 2015 allows us to define block scoped variables. Variables declared using let are not hoisted.
  • var − The JavaScript var keyword is used for creating function scoped variables and are hoisted.
  • const − The const declarations create variables that cannot be reassigned to some other value or redeclared later. It was introduced in ES2015. The variables declared using const are not hoisted.

Following is the code to define variables in JavaScript with let, var and const −

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Define variable in JavaScript</h1>
<div class="result"></div>
<button class="Btn">Click here</button>
<h3>
Click on the above button to declare variables using let, const and var and access them;
</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = "a = " + a + "<br>";
      try {
         resEle.innerHTML += "b = " + b;
      } catch (err) {
         resEle.innerHTML += err + "<br>";
      }
      try {
         resEle.innerHTML += "c = " + c;
      } catch (err) {
         resEle.innerHTML += err + "<br>";
      }
      var a = 22;
      let b = 44;
      const c = 99;
      try {
         c = 44;
      } catch (err) {
         resEle.innerHTML += err + "<br>";
      }
   });
</script>
</body>
</html>

Output

Various ways to define a variable in JavaScript

On clicking the ‘CLICK HERE’ button −

Various ways to define a variable in JavaScript