Block Scope Variable

A block scope variable is a variable that is accessible only inside the block of code where it is declared.

A block means any code written inside { } such as:

  • if blocks

  • for loops

  • while loops

  • function blocks

In JavaScript, variables declared using let and const are block scoped.


example -:


if (true) {

    let x = 10;

    const y = 20;

    console.log(x); // works

}

console.log(x); // Error: x is not defined


  • x and y can only be used inside the { } block
  • Outside the block, they do not exist







Comments