JavaScript Scope - Block Scope with let and const
JavaScript has two main types of scope: global scope and local (function) scope. With the introduction of the let
and const
keywords in ECMAScript 6 (ES6), block scope is also available. Block scope allows you to create variables that are limited in scope to a specific block of code, such as inside a loop or condition. In this guide, we'll explore block scope with let
and const
using practical examples.
Example 1: Block Scope with let
With the let
keyword, you can create variables with block scope. Variables declared with let
are accessible only within the block they are defined in:
if (true) {
let blockScopedVar = 'I am block-scoped';
console.log(blockScopedVar);
}
// Uncommenting the next line would result in an error
// console.log(blockScopedVar);
In this example, blockScopedVar
is only accessible within the if block.
Example 2: Block Scope with const
The const
keyword is used to declare constants, and it also provides block scope. Constants declared with const
cannot be reassigned:
if (true) {
const blockScopedConst = 'I am a constant';
console.log(blockScopedConst);
}
// Uncommenting the next line would result in an error
// blockScopedConst = 'Trying to reassign';
blockScopedConst
is accessible only within the if block, and any attempt to reassign it will result in an error.
Example 3: Block Scope in Loops
Block scope is particularly useful in loops. Variables declared with let
in a loop are unique for each iteration:
for (let i = 0; i < 3; i++) {
console.log('Inside loop:', i);
}
// Uncommenting the next line would result in an error
// console.log('Outside loop:', i);
Here, i
is distinct for each iteration of the loop and is not accessible outside the loop.
Conclusion
Block scope with let
and const</code brings more predictability and control to variable declarations in JavaScript. It allows you to define variables with limited scope, making it easier to avoid unintended variable shadowing and reassignments. It's especially useful in loops and conditional statements.</p>
<p>Consider using block scope with let
and const