Block Scope in JavaScript

2026年8月17日2 次浏览来源:Dev.to阅读原文

Block scope is an important concept in JavaScript.

It means that a variable can be accessed only inside the block where it is declared.

A block is usually written using curly braces .

Blocks can be found in statements, loops, functions, and other parts of JavaScript code.

In JavaScript, and are block-scoped variables.

For example: Output: Here, the variable can be used inside the block.

If we try to use it outside the block, JavaScript will give an error because the variable is not available outside its block.

The same rule applies to .

Output: The variable can only be accessed inside the block.

However, works differently.

It is not block-scoped.

It is function-scoped.

For example: Output: This code works because can be accessed outside the block.

If we try the same thing with : Output: This happens because is block-scoped and cannot be accessed outside the block.

Block scope is useful because it prevents variables from being accidentally used or changed outside the area where they are needed.

It also makes code easier to understand and maintain.

So, the main thing to remember is: and have block scope, while has function scope.

In modern JavaScript, and are generally preferred over .

分享
Baike.dev

baike.dev helps you discover great languages, frameworks, databases, DevOps and cloud-native tools.

Quick links

About

Contribute

Found a great developer tool? Share it with the community.

Submit a tool
© 2026 baike.dev Developer EncyclopediaUpdated daily · Discover great developer tools