Code Highlights logo

Learn

Scope

Block Scope

In JavaScript, block scope refers to the area within if statements, for loops, and functions where variables are only accessible within that block of code. Block scope was introduced in ES6 with the addition of the let and const keywords.

Block scope provides a more controlled and predictable way of managing variables, as they are limited in scope to the block in which they are declared. This can help avoid naming conflicts and unintended side effects.

Declaring Block Scope Variables

To declare variables with block scope, you can use the let or const keywords. These variables will be accessible only within the block they are defined in.

1if (true) {
2 let blockScopedVariable = "Hello";
3 const blockScopedConstant = "World";
4
5 console.log(blockScopedVariable); // Output: Hello
6 console.log(blockScopedConstant); // Output: World
7}
8
9console.log(blockScopedVariable); // Error: blockScopedVariable is not defined
10console.log(blockScopedConstant); // Error: blockScopedConstant is not defined

Unlike variables declared with the var keyword, block-scoped variables are not hoisted to the top of their scope. This means that they can only be accessed within the block they are defined in and are not accessible before their declaration.


Instructions

1.

Declare a variable y inside the block scope (between the curly braces {}) and assign it a value of 5.

2.

Console.log the variable y inside the block scope.

3.

After the block scope, console.log the variable y again.

Sign up to start coding

Already have an account?

Sign In

Course content