JavaScript let Keyword | let Variable

The JavaScript let keyword is used to create a block-scoped variable. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      var num = 2;
      function myFun() {
         for(let i=1; i<=10; i++) {
            let res = num*i;
            document.write(num, " * ", i, " = ", res, "<BR>");
         }
      }
      myFun();
   </script>
   
</body>

</html>
Output

Note - The best practice is, use var to declare a global variable, and let to declare a block-scoped variable.

Unlike var, the let variable can not be re-declared. If you do so, then you will get the error. For example:

javascript let variable

Look at the red underline to x, the variable declared using let. If you will hover on any of the two x, then you will see:

javascript let variable example

JavaScript let Example

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      var num = 2;
      for(let i=1; i<=10; i++)
      {
         res = num*i;
         document.write(num, " * ", i, " = ", res, "<BR>");
      }
   </script>
   
</body>

</html>
Output

The same JavaScript code, written in above example, can also be written as:

<script>
   let num = 2;
   for(var i=1; i<=10; i++)
      document.write(num, " * ", i, " = ", num*i, "<BR>");
</script>

JavaScript Online Test


« Previous Tutorial Next Tutorial »