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


📘 JavaScript letBlock Scoped Variable Declaration

The let keyword was introduced in ES6 (2015) and is used to declare variables that are block-scoped, meaning they are only accessible within the block {} in which they are defined.


🔹 Syntax:
let x = 5;
let name = "John";

🔹 Why Use let?

  • Block scope (unlike var which is function-scoped)

  • Prevents accidental redeclarations in the same scope

  • Safer and more predictable for loops, conditions, and modern JS practices


🧱 Block Scope Example:

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

🚫 Cannot Redeclare let in the Same Scope

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

🔄 But Can Reassign let Variables

let city = "Delhi";
city = "Mumbai"; // ✅ This is allowed

🔄 Difference Between var and let

Feature var let
Scope Function-scoped Block-scoped
Redeclaration Allowed Not allowed
Hoisting Hoisted (value: undefined) Hoisted (but not initialized)
Reassignment Allowed Allowed

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?


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