How to Implement Block scope in JavaScript
Posted on: February 24, 2021 by Deven
In this article, you will learn How to Implement Block scope in JavaScript.
Block scope is a new ES6 feature. You create a new block scope for each set of curly braces. you use let and const keywords to add Variables to block scope.
Implement Block scope in JavaScript
Consider the example below:
function bScope() {
console.log('Scope at top');
let scopeExample = 8;
console.log(scopeExample);
{
console.log('Scope 2 value');
let scopeExample = 'scope 2 value 2 ';
console.log(scopeExample);
}
{
console.log('Scope 3');
let scopeExample = ' scope 3 value';
console.log(scopeExample);
}
}
bScope();
To implement block scope in JavaScript with variables like above, follow the steps below:
- Create a function called
bScope
. console.log
the string as ‘scope at top‘.- Create a variable called
scopeExample
with the value of 8. console.log
the value of the variable calledscopeExample
- Inside the function create a new Block Scope as shown above
- Inside the new Block scope , log the string called ‘scope 2 value’.
- Create a new variable called
scopeExample
, inside that and assign the value ‘scope 2 value 2’ console.log
the value variable scope inside the block scope.- Outside of the block scope we created in step 5, create a new block scope
console.log
the string called ‘scope 3’.- Create a variable inside the scope block with the same name
scopeExample
and assign it the value the ‘scope 3 value‘. console.log
the new variable’s value.- Call
bScope
and test its output
Share on social media
//