javascript

How to Implement Block scope in JavaScript


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:

  1. Create a function called bScope.
  2. console.log the string as ‘scope at top‘.
  3. Create a variable called scopeExample with the value of 8.
  4. console.log the value of the variable called scopeExample
  5.  Inside the function create a new Block Scope as shown above
  6. Inside the new Block scope , log the string called ‘scope 2 value’.
  7. Create a new variable called scopeExample, inside that and assign the value ‘scope 2 value 2’
  8. console.log the value variable scope inside the block scope.
  9. Outside of the block scope we created in step 5, create a new block scope
  10. console.log the string called ‘scope 3’.
  11. Create a variable inside the scope block with the same name  scopeExample and assign it the value the ‘scope 3 value‘.
  12. console.log the new variable’s value.
  13. Call bScope and test its output

Share on social media

//