Open In App

What is block scope in JavaScript?

Block scope in JavaScript refers to the scope of variables and functions that are defined within a block of code, such as within a pair of curly braces {}. Variables and functions declared with let and const keywords have block scope.

Variables declared inside a block are only accessible within that block and any nested blocks. They are not accessible outside of the block in which they are defined. This means that variables declared within a block cannot be accessed before their declaration or outside of the block.



Example: Here, the variable x is declared inside the block created by the if statement. It is accessible within that block but not outside of it. If you try to access x outside of the block, you’ll get a reference error because x is not defined in that scope.




function exampleFunction() {
  if (true) {
    let x = 10; // Variable x has block scope
    console.log(x); // Output: 10
  }
  // console.log(x); // Error: x is not defined
}
 
exampleFunction();

Output

10

Article Tags :