What is a block in JS?
Let's define what a block is before we proceed to understand block scope. A block is known as a compound statement which is a simply a group of multiple statements. You need to use blocks when you need to execute more than one statement. The following example will hopefully clear up any confusion.
{
//compound statements in a block
let a = 1;
console.log(a);
}
if (true) console.log('no block'); // we don't need a block because it is one statement
if (true) { // if we need to use more than one statement we need a block
let a = 1;
console.log(a);
}
What does it mean that let & const are block scoped?
As you can see let & const are block scoped. This means that let & const cannot be accessed outside of this block.
{
var a = 1;
const b = 2;
let c = 3;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
}
console.log(a); // 1
console.log(b); // ReferenceError: b is not defined
console.log(c); // ReferenceError: c is not defined
Top comments (0)