🧮 JavaScript Variables & Data Types
Estimated reading: 4 minutes 12 views

🧠 JavaScript let Keyword – Block Scope & TDZ Explained

💡 Ever encountered weird bugs when using var in a loop or block?
That’s where let comes to the rescue.

The let keyword in JavaScript allows you to declare block-scoped variables—ensuring safer, more predictable behavior in modern JS code. With the introduction of ES6, let quickly became the preferred way to declare variables that change over time.


📘 What You’ll Learn

By the end of this guide, you’ll understand:

  • ✅ How let works in JavaScript with real-world examples
  • ✅ The key differences between let and var
  • ✅ The concept of the Temporal Dead Zone (TDZ)
  • ✅ Best practices to avoid common bugs

let Syntax

let variableName = value;

🔍 Line-by-Line Explanation:

  • let: The keyword used to declare the variable
  • variableName: The name of your variable
  • = value: Assigns a value to the variable (optional at declaration)

📌 Example:

let age = 25;
console.log(age); // Output: 25
  • let age = 25; — Declares a block-scoped variable age and assigns it 25.
  • console.log(age); — Outputs the value 25 to the console.

🧩 Features of let

🔹 1. Block Scope

Variables declared with let are only accessible within the block ({}) they’re declared in.

{
let x = 10;
console.log(x); // 10 ✅ accessible here
}
console.log(x); // ❌ ReferenceError: x is not defined

💡 Block scope prevents variables from leaking into other scopes—reducing side effects.


🔹 2. No Redeclaration in Same Scope

You cannot declare the same variable twice in the same block with let.

let name = "Alice";
// let name = "Bob"; ❌ SyntaxError: Identifier 'name' has already been declared

🛑 This avoids accidental redeclarations—a common source of bugs with var.


🔹 3. Reassignable

Unlike const, you can reassign values to a let variable.

let score = 90;
score = 95; // ✅ Allowed
console.log(score); // 95

📌 let is ideal when the variable value will change later in the program.


🔹 4. Temporal Dead Zone (TDZ)

Variables declared with let exist in a “temporal dead zone” from the start of the block until the declaration is processed.

console.log(a); // ❌ ReferenceError
let a = 5;

💡 Even though a is hoisted, it is not initialized—accessing it before declaration triggers an error.


🔄 let vs var – Comparison Table

Featureletvar
ScopeBlock-scopedFunction-scoped
Redeclaration❌ Not allowed✅ Allowed
HoistingHoisted (TDZ applies)Hoisted (initialized undefined)
Default ValueNot initializedundefined
Use in LoopsSafe (per-iteration scope)Risky (shared scope)

Use let for safer scoping and cleaner code.


🧪 Practical Example – Loop Closure with let vs var

✅ Using let (Correct output):

for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000); // 0, 1, 2
}

Explanation:

  • Each iteration creates a new i bound to that specific loop.
  • setTimeout correctly captures the value.

❌ Using var (Incorrect output):

for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000); // 3, 3, 3
}

Why this happens:

  • var is function-scoped, so all timeouts share the same i.
  • After the loop ends, i becomes 3, and all functions reference that.

✅ Best Practices with let

✔️ Use let when:

  • The variable needs to be reassigned (e.g., loop counters, flags)
  • You want to limit scope to a block or {} to avoid leakage
  • You want to prevent redeclarations within the same block

❌ Avoid let when:

  • You need a constant value → use const
  • You are unaware of scope rules → it might behave unexpectedly

❓ Frequently Asked Questions (FAQs)

❓ Can I use let without assigning a value?

✅ Yes. You can declare and initialize later:

let user;
user = "John";
console.log(user); // John

❓ What happens if I access a let variable before it’s declared?

⛔ You’ll get a ReferenceError due to TDZ:

console.log(a); // ❌ ReferenceError
let a = 10;

❓ Is let hoisted?

Yes, but it’s not initialized until the line is reached. The time between block start and declaration is the Temporal Dead Zone.


❓ Can let be used globally?

Yes, but it’s scoped to the script/module, not added to the global window object like var.

let x = 100;
console.log(window.x); // undefined

📌 Summary

  • let provides block-level scoping, protecting variables from unintentional usage across blocks.
  • Unlike var, it prevents redeclaration and avoids closure bugs in loops.
  • It introduces the concept of Temporal Dead Zone (TDZ) for safer coding practices.

👉 Mastering let is essential for writing modern, bug-free JavaScript.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

JavaScript Let

Or Copy Link

CONTENTS
Scroll to Top