Let in Javascript | Scope, Example

Let in Javascript is a keyword that is used to declare a block-level variable rather than a global variable or variable in a function block.

Javascript let keyword follows the same definition as var, with one exception that it is tied to the block scope, not the function scope.

That is, a variable defined with let keyword is visible only within the scope in which it is defined.

The syntax to declare a variable using let keyword is as follows:

let language = 'Javascript'; // Declare and Initialize a variable.
Or,
let language; // Declare a variable.
language = 'Javascript'; // Initialize a variable.

Multiple variables can also be declared using let keyword in a single line like this:

let x, y, z; // Declaration of 3 variables.
let num = 20, char = 'A'; // Declaration and Initialization of 2 variables.

Let keyword was introduced in ECMAScript 6 (ES6) that is a new standard feature of Javascript.

Why do we need let keyword in Javascript?


When a variable is declared using var keyword in javascript, it is called function scoped variables. They are accessible globally to the script or throughout the script if declared outside the function.

Similarly, if the function scoped variables are declared inside a function, they are accessible throughout the function, but not outside the function.

Let’s understand it with the help of an example program in which we will declare a function scoped variables and see the output.

Program code 1:

<html>
<body>
<script>
    var x = 10; // accessible globally.
    function myFunction()
    {
        document.write(x +"<br>");
        var y = 20; // accessible throughout the function.
        if(true)
       {
          var z = 30; // accessible throughout the function.
          document.write(y+ "<br>");
        }
      document.write(z);
    }
 myFunction(); // Calling function.
</script>
</body>
</html>
Output of the code:
         10
         20
         30

As you see in the above script code, the variable z is a local variable inside the if statement. The variable z is still accessible after the if statement has finished execution.

To overcome this problem, Javascript has introduced let keyword in ES6 which can be used for creating variables that are block scoped.

In the above script code, if we use let instead of var, the variable z would not be visible (accessible) after the loop is completed.

Block Scoped Variables in Javascript (let keyword Scope in Javascript)


Variables that are defined using the let keyword are called block scoped variables in javascript. The block scoped variables are locked into a block.

That is, they exist only within the current block. They cannot be accessed outside a block and they are removed from the memory as soon as the block finishes the execution.

A block is a group of zero or more statements in Javascript that is created with curly braces ({ . . . .}). A pair of curly braces can be put anywhere in the script to define a new block scope.

The block-scoped variables work the same way as function scoped variables when declared outside the function, they are accessed globally.

But when the block scoped variables are defined inside a block, they are only accessible inside the block in which they are defined, but not outside the function.


Note: The extent or area of the script code from which variable can be accessed is called variable scope.


Let’s take an example script in which we will declare variables using let keyword and see the output.

Program code 2:

<html>
<body>
<script>
   let x = 20; // accessible globally.
   function myFunction()
   {
      document.write(x+ "<br>");
      let y = 30; // accessible throughout the function.
      if(true)
      {
          let z = 40; // accessible only inside if statement.
          document.write(y+ "<br>");
       }
    document.write(z); // Reference Error Exception.
   }
  myFunction(); // Calling function.
</script>
</body>
</html>
Output of code:
           20
           30
          Reference Error Exception

If you will execute the above script code, the last statement “document.write(z);” would generate an error because the definition of z is removed as soon as the loop of if statement completes.

In other simple words, the variable z is not accessible outside the block of if statement.


Let’s take one more simple example script based on it.

Program code 3:

<html>
<body>
<script>
   for(var x = 1; x < 5; x++)
    {
       document.write(x+ “ ”); // Output: 1 2 3 4
    }
   document.write(x); // Output: 5 because variable x is accessible here.
   for(let y = 1; y < 10; y++)
   {
       document.write(y+ “ ”); // Output: 1 2 3 4
    }
  document.write(y); // Error! y is undefined because variable y is not accessible outside for loop.
</script>
</body>
</html>

As you can see in the above script code, the variable y declared with let keyword is accessible inside the for loop, but not outside the for loop.

Variables Redeclaration in Javascript


We can easily redeclare a variable using var keyword that is already declared using var keyword in the same scope. Consider a simple example below:

Program code 4:

<html>
<body>
     <h2>Redeclaration of a variable using var keyword</h2>
<script>
     var city = "Ranchi";
     var city = "Dhanbad"
     document.write("Name of city: " +city+ "<br>");
    function myFunction()
    {
       var city = 'Mumbai';
       var city = 'New York';
       document.write("Name of city: " +city);
    }
   myFunction(); // Calling function.
</script>
</body>
</html>
Output of code:
            Redeclaration of a variable using var keyword
            Name of city: Dhanbad
            Name of city: New York

As you observe in the code, variables declared with var keyword can be easily redeclared in the same scope. But variables defined using let keyword do not function in the same way.


If we declare a variable using let keyword that is already declared using let keyword in the same scope, Java interpreter will throw TypeError exception.

Consider the below simple script code.

Program code 5:

<html>
<body>
     <h2>Variables cannot be redeclared using let keyword</h2>
<script>
   let x = 20;
   let x = 40; // TypeError because of redeclaration.
  document.write("Value of x: "+x+ "<br>");
  function myFunction()
  {
      let y = 100;
      let y = 200; // TypeError
      document.write("Value of y: " +y+ "<br>");
   }
  myFunction(); // Calling function.
</script>
</body>
</html>

When we define a variable with a name using let keyword or var keyword that is already defined in any function or sub-block respectively, it will be considered different variables.

In other simple words, the redeclaration of a variable using let keyword or var keyword in the different block scope is allowed.

Let’s take a simple example program based on it.

Program code 6:

<html>
<body>
<script>
    var x = 20;
    let y = 30;
  function myFunction()
  {
     var x = 40; // Different variable because of different block scope.
     let y = 50; // Different variable because of different block scope.
     if(true)
     {
        var x = 60; // Overwritten because of the same block scope.
         let y = 70; // Different variable because of the different block scope.
        document.write(x+ "<br>");
        document.write(y + "<br>");
     }
   document.write(x+ "<br>");
   document.write(y+ "<br>");
 }
 myFunction(); // Calling function.
 document.write(x+ "<br>");
 document.write(y);
</script>
</body>
</html>
Output of code:
                 60
                 70
                 60
                 50
                 20
                 30

Variables Reassignment in Javascript


The ability to change or reassign the value of a variable at any time is called variable reassignment in javascript.

There are two ways to reassign the value of a variable that are as follows:

  • Using var keyword
  • Using let keyword

Let’s take a very simple example program in which we will reassign the value of variables using var and let keywords respectively and see the output.

Program code 7:

<html>
<body>
<script>
// Declared and assigned using var.
     var name = 'John';
     document.write('Name: ', name, '<br>');
// Value reassigned.
     name = 'Ivaan';
    document.write('Reassigned name: ', name, '<br>');

  {
// Declared and assigned using let.
     let city = 'New York';
     document.write('City: ', city, '<br>');
// Value reassigned.
     city = 'Dhanbad';
     document.write('Reassigned city: ', city)
  }
</script>
</body>
</html>
Output of code:
              Name: John
              Reassigned name: Ivaan
              City: New York
              Reassigned city: Dhanbad

Variables Hoisting in Javascript


The variable instantiation and assignment at the time of variable’s declaration is called variable hoisting. Variables declared using var keyword can be reassigned, have function scope and variable hoisting.

It means that variables declared with var are hoisted to the top of the scope block, can be initialized at any time, and used or accessed before they are declared.

Consider the below example script code where variable declared using var keyword is hoisted.

Program code 8:

<html>
<body>
<script>
      document.write(x); // Accessing before declaration and initialization.
      var x = 20;
</script>
</body>
</html>
Output of code:
              Undefined

Variables defined using let keyword are not subject to variable hoisting. It means that accessing variable defined using let before assignment will throw a runtime error.

Consider the below example script code in which variable defined with let keyword are not hoisted.

Program code 9:

<html>
<body>
<script>
     document.write(x); // Accessing before declaration and initialization.
     let x = 20;
</script>
</body>
</html>
Output of code:
              ReferenceError: Cannot access 'x' before initialization

Advantage of using Let keyword in Javascript


There are several advantages of using let keyword with variables declaration. They are as follows:

  • Let keyword makes script more memory friendly.
  • It helps to prevent the scoping mistake.
  • It prevents the accidental bugs in the script code.
  • Let keyword makes the script code easier to read.

var vs let, which should one to use?


When writing the code in ES6, it is recommended to use the let keyword but if you are already addicted to use var keyword and also comfortable in using then you can still use it.


Hope that this tutorial has elaborated almost all the important points concerning let keyword in Javascript with example programs. I hope that you will have understood scope of let keyword in Javascript.
Thanks for reading!!!