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 follow 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.

We can also declare multiple variables 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.

JavaScript Let keyword

Why do we need let keyword in JavaScript?


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

Similarly, if the function scoped variable is declared inside a function, it is 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:

<script>
  var x = 10; // accessible globally.
// Create a function named myFunction.
  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>
Output:
      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 we can use 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 completes.

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 where we can access variable is called variable scope.


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

Program code 2:

<script>
  let x = 20; // accessible globally.
// Create a function named myFunction.
  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>
Output:
       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 program based on it.

Program code 3:

<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>

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 where we re-declare a variable using var keyword.

Program code 4:

<script>
  var city = "Ranchi";
  var city = "Dhanbad" // redeclaration of a variable.
  document.write("Name of city: " +city+ "<br>");
  function myFunction()
  {
    var city = 'Mumbai';
    var city = 'New York'; // redeclaration of variable.
    document.write("Name of city: " +city);
   }
 myFunction(); // Calling function.
</script>
Output:
       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, JavaScript interpreter will throw TypeError exception.

Consider the below simple script code where we will redeclare variables using let keyword and see what happen?

Program code 5:

<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>

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:

<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>
Output:
        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:

<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>
Output:
      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 a variable declared using var keyword is hoisted.

Program code 8:

<script>
      document.write(x); // Accessing before declaration and initialization.
      var x = 20;
</script>
Output:
      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:

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

Advantage of using Let keyword


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, we will recommend using the let keyword, but if you are already habit to use var keyword and are 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!!!
Next ⇒ Const in JavaScript⇐ Prev Next ⇒

Please share your love