Block scope in JavaScript

Rumman Ansari   Software Engineer   0000-00-00 00:00:00   154  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

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:

<span class="pln">
</span><span class="kwd">function</span><span class="pln"> exampleFunction</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="kwd">true</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">let</span><span class="pln"> x </span><span class="pun">=</span><span class="pln"> </span><span class="lit">10</span><span class="pun">;</span><span class="pln"> </span><span class="com">// x is only accessible within this block</span><span class="pln">
    console</span><span class="pun">.</span><span class="pln">log</span><span class="pun">(</span><span class="pln">x</span><span class="pun">);</span><span class="pln"> </span><span class="com">// Output: 10</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">

  </span><span class="com">// Uncommenting the line below would result in an error, as x is not accessible here</span><span class="pln">
  </span><span class="com">// console.log(x); // Error: x is not defined</span><span class="pln">
</span><span class="pun">}</span><span class="pln">

exampleFunction</span><span class="pun">();</span><span class="pln">
</span>

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.

MCQ Available

There are 11 MCQs available for this topic.

11 MCQTake Quiz

No Questions Data Available.
No Program Data.

Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.