JavaScript let Keyword

JavaScript let Keyword

Learn how the let keyword works in JavaScript with real-world examples, scope rules, and ES6 best practices.

In JavaScript, the let keyword is used to declare a block-scoped variable, meaning the variable is accessible only within the block where it is defined. It was introduced in ES6 (ECMAScript 2015) to address the limitations and unexpected behavior associated with the older var keyword.

Unlike var, variables declared with let do not get hoisted to the top of their enclosing function or global scope. Instead, they exist only within their specific block (such as inside { }), which helps prevent accidental reassignments and scope-related bugs.

Using let makes your code more predictable, readable, and easier to maintain. For this reason, it is widely recommended in modern JavaScript development and is considered a best practice when working with variables that may change over time.

Ways to Declare Variables in JavaScript

In JavaScript, variables can be declared using three different keywords: var, let, and const. Each keyword defines how the variable behaves in terms of scope, reassignment, and best use cases.

  • var – Function-scoped and part of older JavaScript versions; generally avoided in modern code
  • let – Block-scoped and ideal for variables that may change during execution
  • const – Block-scoped and used for values that should not be reassigned

Before the introduction of ES6, JavaScript supported only two types of variable scope:

  • Global Scope – Variables accessible throughout the entire program
  • Function Scope – Variables accessible only within the function where they are declared

With the introduction of let, JavaScript gained Block Scope. This enhancement allows variables to exist only within a specific block (such as loops or conditional statements), greatly improving code safety, readability, and predictability.

Syntax of let

let variableName;
    

Example 1: Global Scope

A variable declared outside of any function is said to have global scope. Such variables are accessible from anywhere in the JavaScript program, including inside functions.

In the example below, the variable x is declared in the global scope. Both the main program and the show() function can access and use this value without any restrictions.

JavaScript Example

let x = 20;

console.log("Outside the function, x = " + x);

function show() {
    console.log("Inside the function, x = " + x);
}

show();
        
Try it Yourself »

Example 2: Function Scope

A variable declared with let inside a function has function scope. This means the variable is accessible only within the function where it is defined.

In this example, the variable num is declared inside the show() function. Attempting to access it outside the function results in a ReferenceError, which helps prevent accidental data leaks and improves code safety.

JavaScript Example

function show() {
    let num = 15;
    console.log("Inside the function, num =", num);
}

show();

// The line below will throw an error because 'num' is not defined here
console.log("Outside the function, num =", num);
        
Try it Yourself »

Example 3: Block Scope

A variable declared with let inside a block ({ }) has block scope. This means the variable exists only within that specific block, such as inside conditional statements or loops, and cannot be accessed from outside.

In the example below, the variable message is declared inside an if block. It is available only while the condition executes. Attempting to access it outside the block results in a ReferenceError, helping prevent unintended side effects.

JavaScript Example

if (true) {
    let message = "Block scope example";
    console.log("Inside the block:", message);
}

// The line below will throw an error because 'message' is block-scoped
console.log("Outside the block:", message);
        
Try it Yourself »

Example 4: Redeclaring Variables in Different Blocks

JavaScript allows variables declared with let to use the same name in different blocks. This is known as block-level shadowing. However, redeclaring a variable with let in the same scope is not permitted and will result in a SyntaxError.

In the example below, the variable num is declared in the outer scope and again inside a separate block. These two variables are completely independent because they exist in different scopes.

JavaScript Example

let num = 23;

{
    let num = 15; // This 'num' is block-scoped
    console.log("num inside the block =", num);
}

console.log("num outside the block =", num);

// ❌ The line below would cause a SyntaxError
// let num = 89;
        
Try it Yourself »

How is let Different from the var Keyword?

The key difference between let and var lies in how they handle scope, hoisting, and redeclaring variables. While variables declared with var are function-scoped, those declared with let are block-scoped, meaning they exist only within the block in which they are defined.

This difference makes let significantly safer and more predictable in real-world applications. It helps prevent accidental variable overwrites, reduces scope-related bugs, and improves overall code readability. For these reasons, let is the preferred choice over var in modern ES6+ JavaScript development.

Example 5: var – Function Scope

Variables declared using var are function-scoped, not block-scoped. This means that even if a var variable is declared inside a block ({ }), it is still accessible throughout the entire function.

Additionally, var declarations are hoisted to the top of their function scope and initialized with undefined. This behavior can lead to unexpected results and is one of the main reasons why var is discouraged in modern JavaScript development.

JavaScript Example

function checkVarScope() {
    console.log("Before block x =", x);

    {
        var x = 28;
    }

    console.log("After block x =", x);
}

checkVarScope();
        
Try it Yourself »

Example 6: let – Block Scope

Variables declared using let are block-scoped, meaning they exist only within the block ({ }) in which they are defined. Any attempt to access a let variable outside its block results in a ReferenceError.

In this example, the variable x is declared inside a nested block within a function. While it is accessible inside that block, it is completely unavailable outside of it—demonstrating the strict block-level scoping behavior of let.

JavaScript Example

function checkLetScope() {
    {
        let x = 37;
        console.log("Inside block x =", x);
    }

    // 'x' is not accessible here
    console.log("Outside block x =", x);
}

checkLetScope();
        
Try it Yourself »

Loop Scope in JavaScript

Variables declared inside loops behave very differently depending on whether let or var is used. Understanding this distinction is critical, as improper scoping with var has historically been a common source of bugs in JavaScript applications.

let: Loop Scope Example

When let is used to declare a loop variable, that variable is block-scoped to the loop itself. As a result, the loop variable does not affect variables with the same name outside the loop, making the behavior predictable and safe.

In the example below, the outer variable i remains unchanged after the loop finishes execution, even though the same variable name is used inside the loop.

JavaScript Example

function checkLoopScope() {
    let i = 4;

    for (let i = 0; i < 10; i++) {
        // loop logic
    }

    console.log("Final value of i outside the loop:", i);
}

checkLoopScope();
        
Try it Yourself »

var: Loop Scope Example

When var is used to declare a loop variable, it does not create a new block scope. Instead, the variable is function-scoped, meaning the same variable is shared between the loop and the surrounding function.

As a result, any changes made to the loop variable persist outside the loop after it finishes executing. This behavior often leads to bugs and unexpected results, especially in larger or asynchronous programs.

JavaScript Example

function checkLoopScope() {
    var i = 4;

    for (var i = 0; i < 10; i++) {
        // loop logic
    }

    console.log("Final value of i outside the loop:", i);
}

checkLoopScope();
        
Try it Yourself »

Redeclaration Rules: var vs let

JavaScript handles variable redeclaration differently depending on whether var or let is used. Understanding these rules is important to avoid unexpected errors and to write clean, maintainable code.

Variables declared with let cannot be redeclared in the same scope, which helps prevent accidental overwrites. However, the same variable name can be reused in separate blocks because each block creates its own scope.

// ✔️ Redeclaration in different blocks is allowed
let status = "active";

if (status === "active") {
    let status = "processing";
    console.log("Inside if block:", status);
}

if (status === "active") {
    let status = "completed";
    console.log("Inside second block:", status);
}

console.log("Outside blocks:", status);