Block scope in JavaScript

Rumman Ansari   Software Engineer   0000-00-00 00:00:00   22 Share
Subject Syllabus DetailsSubject Details 11 MCQ
☰ Table of Contents

Table of Content:


Block scope refers to the area within your code where a variable is accessible. In JavaScript, variables declared using the let and const keywords have block scope, meaning they are only accessible within the block of code (enclosed by curly braces) where they are defined.

Here's an example to illustrate block scope:


function exampleFunction() {
  if (true) {
    let x = 10; // x is only accessible within this block
    console.log(x); // Output: 10
  }

  // Uncommenting the line below would result in an error, as x is not accessible here
  // console.log(x); // Error: x is not defined
}

exampleFunction();

In the example above, the variable x is declared using let inside the if block, making it accessible only within that block. Attempting to access x outside of the block will result in an error.

In contrast, variables declared with var have function scope rather than block scope. This means they are accessible throughout the entire function, regardless of where they are declared within the function. The introduction of let and const in ECMAScript 6 (ES6) addressed some of the issues related to variable scoping in JavaScript and provided more predictable and controllable scoping behavior.