DEV Community

kim-jos
kim-jos

Posted on • Edited on

What is Block Scope in JS?

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);
}
Enter fullscreen mode Exit fullscreen mode

What does it mean that let & const are block scoped?

Let's use an example.
image

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)