JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Let


In JavaScript, let is a keyword used to declare variables that are block-scoped. Introduced in ES6 (ECMAScript 2015), let provides more predictable behavior than the older var keyword and is widely used in modern JavaScript programming. Unlike var, which is function-scoped, let restricts the variable’s accessibility to the block, statement, or expression where it is defined. This scoping helps prevent unintended side effects and makes code easier to debug and maintain.

In this chapter, you will learn about the let keyword, its scope, rules for reassignment and redeclaration, hoisting behavior, practical usage, common mistakes, best practices, and real-world applications.

What Is let

The let keyword is used to declare variables that can be updated but cannot be redeclared in the same scope. Variables declared with let are accessible only within the block where they are defined. This prevents variables from leaking into the global scope or other functions, reducing potential bugs, especially in larger applications.

Example

let name = "Ananya";
console.log(name); // Outputs: Ananya

Here, the variable name stores the string "Ananya" and can be used within the block where it is declared.

Scope of let

Variables declared with let are block-scoped. A block is defined by curly braces {}. This differs from var, which is function-scoped and can be accessed outside blocks unintentionally.

Example

{
    let name = "Ishita";
    console.log(name); // Outputs: Ishita
}

console.log(name); // ReferenceError: name is not defined

Variables inside the block exist only within that block. Accessing them outside results in an error.

Nested Block Scope

let name = "Sanya";

{
    let name = "Riya"; // Separate variable within this block
    console.log(name); // Outputs: Riya
}

console.log(name); // Outputs: Sanya

Variables in nested blocks do not overwrite outer block variables.

Reassignment

Variables declared with let can be updated (reassigned) after their initial declaration.

Example

let studentName = "Sanya";
console.log(studentName); // Outputs: Sanya

studentName = "Riya";
console.log(studentName); // Outputs: Riya

This demonstrates the flexibility of let while maintaining block-level scope.

Redeclaration

A variable declared with let cannot be redeclared in the same scope. Attempting to do so results in a syntax error.

Example

let girlName = "Mira";
// let girlName = "Diya"; // SyntaxError: Identifier 'girlName' has already been declared

This prevents accidental redeclaration, which can lead to confusing behavior.

Hoisting Behavior

Variables declared with let are hoisted but remain in a temporal dead zone (TDZ) until their declaration is evaluated. Accessing them before declaration causes an error.

Example

// console.log(name); // ReferenceError: Cannot access 'name' before initialization
let name = "Diya";
console.log(name); // Outputs: Diya

Unlike var, let does not allow the variable to be accessed before declaration, improving code safety.

Loop Example

let is useful in loops because it preserves block scope for each iteration, unlike var.

Example

let girls = ["Ananya", "Ishita", "Sanya", "Riya", "Mira"];

for (let i = 0; i < girls.length; i++) {
    let currentGirl = girls[i];
    console.log("Hello, " + currentGirl + "!");
}

Output:

Hello, Ananya!
Hello, Ishita!
Hello, Sanya!
Hello, Riya!
Hello, Mira!

Each iteration has its own block-scoped variable currentGirl, preventing issues that occur with var.

Nested Loops

let names = ["Anika", "Diya", "Mira"];
for (let i = 0; i < names.length; i++) {
    for (let j = 0; j < 2; j++) {
        let repeatedName = names[i];
        console.log(repeatedName + " iteration " + (j + 1));
    }
}

Output:

Anika iteration 1
Anika iteration 2
Diya iteration 1
Diya iteration 2
Mira iteration 1
Mira iteration 2

Each loop has independent block-scoped variables.

Practical Examples

Example 1: Age Assignment

let girlName = "Diya";
let age = 22;

console.log(girlName + " is " + age + " years old.");
age = 23;
console.log(girlName + " is now " + age + " years old.");

Example 2: Full Name

let firstName = "Anika";
let lastName = "Sharma";

let fullName = firstName + " " + lastName;
console.log("Full Name: " + fullName);

Example 3: Loop Through Names

let girls = ["Ananya", "Ishita", "Sanya", "Riya", "Mira"];

for (let i = 0; i < girls.length; i++) {
    console.log(girls[i] + " is ready for the coding challenge.");
}

Output:

Ananya is ready for the coding challenge.
Ishita is ready for the coding challenge.
Sanya is ready for the coding challenge.
Riya is ready for the coding challenge.
Mira is ready for the coding challenge.

Example 4: Updating Values Dynamically

let score = 10;
console.log("Initial score:", score);

score += 5;
console.log("Score after bonus:", score);

score--;
console.log("Score after penalty:", score);

Common Mistakes

  • Redeclaring the same let variable in the same scope.

  • Accessing let variables outside their block.

  • Confusing let with var in loops.

  • Declaring unnecessary global let variables.

Best Practices

  • Use let for variables that need to change.

  • Declare variables at the start of blocks or functions.

  • Use descriptive variable names.

  • Avoid global variables unless required.

  • Use const for variables that should not change.

Real-World Applications

  • Storing dynamic user input such as names, ages, or form data.

  • Looping through arrays and lists safely.

  • Managing temporary states in functions or blocks.

  • Updating values in calculations or conditional logic.

Summary

The let keyword declares block-scoped variables that can be reassigned but not redeclared in the same scope. It prevents common scope-related issues, especially in loops and nested blocks. let provides safer, more predictable behavior than var and is a key part of modern JavaScript programming. Variables declared with let allow flexible, maintainable, and clear code. This chapter included examples covering declaration, reassignment, redeclaration, loops, hoisting, and practical usage.


Practice Questions

Q1. How do you declare a variable named age using the let keyword and assign it the value 30?

Q2. How do you update a variable city declared with let to change its value from "Delhi" to "Mumbai"?

Q3. How do you demonstrate block scope by declaring a let variable inside a block and trying to access it outside the block?

Q4. How do you show that a variable declared with let cannot be redeclared in the same scope?

Q5. How do you use a let variable in a for loop to iterate from 1 to 5 and print each number?

Q6. How do you write a JavaScript code that declares the same variable name with let inside and outside a block to show they are treated separately?

Q7. How do you declare a variable x with let, assign it 10, then reassign it to 20 and log the result?

Q8. How can you demonstrate that let declarations are hoisted but not initialized?

Q9. How do you write a function with a let variable that does not affect the global variable with the same name?

Q10. How do you write a condition using if block where a let variable is declared inside and used only within that block?


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top