JavaScript Scope - Block-Level Scope with let and const


In JavaScript, variables declared using let and const have block-level scope. This means they are limited in scope to the block, statement, or expression where they are defined. In this guide, we'll explore block-level scope using let and const and provide examples to illustrate their usage.


Using let for Block-Level Scope


The let keyword allows you to declare variables with block-level scope. Variables declared with let are limited to the block they are defined in:


if (true) {
let x = 10;
console.log(x); // x is accessible here
}
console.log(x); // x is not accessible here

Using const for Block-Level Scope


Variables declared with const also have block-level scope, and they cannot be reassigned after declaration:


if (true) {
const pi = 3.14;
console.log(pi); // pi is accessible here
}
console.log(pi); // pi is not accessible here

Block-Level Scope in Loops


Block-level scope is particularly useful in loops, where variables can be safely isolated within each iteration:


for (let i = 0; i < 5; i++) {
console.log(i); // i is isolated within each iteration
}
console.log(i); // i is not accessible here

Block-Level Scope in Functions


Block-level scope is also applicable within functions:


function exampleFunction() {
let message = "Hello, world!";
if (true) {
let message = "Goodbye, world!";
console.log(message); // Inner block message
}
console.log(message); // Outer block message
}
exampleFunction();

Conclusion


Block-level scope using let and const

Happy coding!