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;
            console.log(res);
         }
      }
      myFun();
   </script>
   
</body>
</html>

The snapshot given below shows the sample output produced by above example:

javascript let keyword example

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++)
         console.log(num*i);
   </script>
   
</body>
</html>

The output should be:

let variable javascript example

JavaScript Online Test


« Previous Tutorial Next Tutorial »