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.
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
Declare a variable y
inside the block scope (between the curly braces {}
) and assign it a value of 5
.
Console.log the variable y
inside the block scope.
After the block scope, console.log the variable y
again.
Sign up to start coding
Already have an account?
Sign In