Monday, August 4, 2025

Javascript Module 46

  Module 46 : Let, Const, and Block Scope 

1. Introduction to Variable Declaration

               










 variable in JavaScript

Types of variable declarations: var, let, const

History: ES5 vs ES6+


2. Understanding var, let, and const

Feature

var

let

const

Scope

Function Scope

Block Scope

Block Scope

Hoisting

Yes (initialized undefined)

Yes (but TDZ)

Yes (but TDZ)

Re-declaration

Allowed

Not allowed

Not allowed

Re-assignment

Allowed

Allowed

Not allowed

Temporal Dead Zone

No

Yes

Yes



3. Block Scope 

Block scope means a variable is only accessible within the {} where it's defined.

 Example:

{ let a = 10; const b = 20; var c = 30; } console.log(a); // ReferenceError console.log(b); // ReferenceError console.log(c); // 30

a and b are block-scoped → inaccessible outside the block

c is function-scoped (or global if not in a function) → accessible


4. Temporal Dead Zone (TDZ)

               











TDZ is the time between the block start and the point where let or const is declared.

{ // TDZ starts console.log(x); // ReferenceError: Cannot access 'x' before initialization let x = 5; }


5. Const Keyword Deep Dive

const creates immutable bindings, not immutable objects.

You cannot reassign the variable, but you can modify the contents (if it's an object or array).

const arr = [1, 2, 3]; arr.push(4); // ✅ Allowed arr = [4, 5, 6]; // ❌ TypeError


6. Usage Scenarios

Use Case

Use let or const?

Iterating with counters (for)

let

Declaring a constant API URL

const

Declaring an object to be mutated

const

Temporary mutable variable in block

let



Examples & Explanation

 Example 1: Using let in a loop

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

Each iteration has its own i due to block scope.


Example 2: Using var in a loop

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

var is function-scoped, so the same i is used for all timeouts.


 Example 3: TDZ Explanation

function test() { console.log(a); // ReferenceError let a = 5; } test();

Variable a is hoisted but not initialized, so it’s in TDZ.


 Exercises

🔸 Exercise 1: Rewrite using let and const

              










Before (using var):

var name = "Alice"; function greet() { if (true) { var name = "Bob"; console.log(name); // Bob } console.log(name); // Bob (unexpected!) } greet();

After:

const name = "Alice"; function greet() { if (true) { let name = "Bob"; console.log(name); // Bob } console.log(name); // Alice (expected!) }


🔸 Exercise 2: TDZ Identification

Find the error:

function getValue() { console.log(value); // ? let value = 10; } getValue();

✅ Solution: ReferenceError due to TDZ


🔸 Exercise 3: Const Object Mutation

const user = { name: "Jane" }; user.age = 25; console.log(user); // What is the output? user = {}; // Is this allowed?

✅ Answer:

Adding properties is allowed

Reassigning the user object is not allowed


Key Concepts

The difference in scoping (function vs block)

TDZ and how it causes runtime errors

 const does not make an object immutable

advantages of let and const over var

 prefer const, use let when mutation is needed

    Strategy

Start with a history of var and show its pitfalls.

Use analogies, e.g., TDZ as a “no-go zone” until initialization.

Reinforce learning with live code tests in console or JSFiddle/CodePen.

Use comparison tables, debugging walkthroughs, and group code rewrites.


Write a function that:

Accepts a number

Declares a let variable inside a loop to count down from the number

Uses a const array to store each countdown number

Returns the array

function countdown(n) { const result = []; for (let i = n; i >= 0; i--) { result.push(i); } return result; } console.log(countdown(5)); // [5, 4, 3, 2, 1, 0]


 Research 

   

      




       


 Web Docs: let

 Web Docs: const

 Proposal History

ES6 Language Specification

Always use const by default

Use let only when reassignment is necessary

Avoid var in modern JS unless dealing with legacy code


🧠 Summary

let and const introduce block-level scope, helping reduce bugs from var

Use const for constants and objects that won’t be reassigned

Understand and avoid the Temporal Dead Zone

Know when to use which declaration for safe and readable code


if you use a let variable before it is declared.

                 










const variable be changed if it holds an object.

the difference between let and var inside a block.

 use let over const.

 Temporal Dead Zone.



No comments:

Post a Comment

Javascript Module 78

  Javascript   Module 78 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test...