DEV Community

kim-jos
kim-jos

Posted on • Edited on

3 2

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay