Javascript : Block Scoped Variables & Functions

This article highlights new feature introduced in ECMAScript 6 called “Block Scoped Variable” & “Block Scoped Functions“. In internet, you may find many articles on block scoped variable and functions. But this is an attempt to present the topic in as much simplest and easiest way as I can so that developers of each level can understand the concept clearly.

Hope everyone reading this article knows about the concept of Block Scope. In general, SCOPE refers to the range to which the particular object is relevant and BLOCK SCOPE refers to the range inside the block. So lets dive into this concept quickly without wasting much time.

Block Scoped Variables

As per ECMAScript 6 standard, a new keyword introduced named as LET. Its somehow similar to the keyword VAR, though it has some differences.

Both VAR & LET keyword are same in context of declaring variable but different regarding to its scope. LET is scoped to the nearest enclosing block whereas VAR is scoped to the nearest function block. If both the keyword present outside the block, then it behaves similarly as global.

Example 1 (with VAR keyword) :-

<script>
    for (var i = 0; i < 10; i++) {
        // do something
    }

    document.write(i);
</script>

// Output : 10

Example 1 (with LET keyword) :-

<script>
    for (let i = 0; i < 10; i++) {
        // do something
    }

    document.write(i);
</script>

// Output : ReferenceError: i is not defined

For the above example, with LET keyword, the variable i is locally blocked to the for loop, but in case of VAR keyword, the variable i is global.

Example 2 (with VAR keyword) :-

<html>
    <head>
        <title>Testing Block Scoped Variables</title>
        <style>
            div {
                width: 100px;
                height: 100px;
                background-color: #ccc;
                border: 1px solid #000;
                display: inline-block;
                font-size: 30px;
                text-align: center;
                cursor: pointer;
            }
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                for(var i = 1; i < 4; i++) {
                    $("#dv_blockScope" + i).on('click', function () {
                        alert(i);
                    });
                }
            });
        </script>
    </head>

    <body>
        <div id="dv_blockScope1">1</div>
        <div id="dv_blockScope2">2</div>
        <div id="dv_blockScope3">3</div>
    </body>
</html>

// This will output 4 on each click as it refers to the same object.

In order to fix the above issue, we need to wrap the click event in an anonymous function and pass i as argument. But without creating function, we can fix the above issue by just using LET instead of VAR as shown in code below.

Example 2 (with LET keyword) :-

<html>
    <head>
        <title>Testing Block Scoped Variables</title>
        <style>
            div {
                width: 100px;
                height: 100px;
                background-color: #ccc;
                border: 1px solid #000;
                display: inline-block;
                font-size: 30px;
                text-align: center;
                cursor: pointer;
            }
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                for(let i = 1; i < 4; i++) {
                    $("#dv_blockScope" + i).on('click', function () {
                        alert(i);
                    });
                }
            });
        </script>
    </head>
    <body>
        <div id="dv_blockScope1">1</div>
        <div id="dv_blockScope2">2</div>
        <div id="dv_blockScope3">3</div>
    </body>
</html>

// This will output the respective number i.e. 1, 2 & 3.

Block Scoped Functions

According to ECMAScript 6, the syntax for block scoped functions got changed. The function scope can be written in a different and easy manner. Lets go through one example to differentiate.

Example 3 (syntax with ES5) :-

<script>
    (function() {
        // first function
        var operation = function (a, b) {
            return a + b + '<br>';
        }

        document.write(operation(1, 2));  // O/P - 3 (executes 1st function)

        (function () {
            // second function
            var operation = function(a, b) {
                return a * b + '<br>';
            }
    
            document.write(operation(2, 3));  // O/P - 6 (executes 2nd function)
        })();

        document.write(operation(2, 3));  // O/P - 5 (executes 1st function, as it belongs to the main block)
    })();
</script>

The above example contains same method but in different function block. There are some specific notations I used in the above example which let me note it down.
1. While declaring a self executable function, we had to use (function() { .. })();.
2. We had to use var = function (param1, param2, …) { … }; notation to define a function.

But with ECMAScript 6, lets see how the scoped definition for function changed.

Example 3 (syntax with ES6) :-

<script>
    {
        // first function
        function operation(a, b) {
            return a + b + '<br>';
        }

        document.write(operation(1, 2));  // O/P - 3 (executes 1st function)

        {
            // second function
            function operation(a, b) {
                return a * b + '<br>';
            }

            document.write(operation(2, 3));  // O/P - 6 (executes 2nd function)
        }

        document.write(operation(2, 3));  // O/P - 5 (executes 1st function, as it belongs to the main block)
    };
</script>

Check the syntax with ES6.
1. We no need to write a complicated line like this (function() { .. })();. We only have to write { .. };, plain & simple.
2. We no need to use var = function (param1, param2, …) { … };, instead we can directly write function (param1, param2, …) { … }.

Example 4 (syntax with ES5) :-

<script>
    (function foo() {
        let x = 1;

        (function foo() {

            let x = 2;
            document.write(x + '<br>');  // O/P - 2

        })();

        document.write(x + '<br>');  // O/P - 1
    })();
</script>

Example 4 (syntax with ES6) :-

<script>
    {
        let x = 1;

        {
            let x = 2;
            document.write(x + ' <br>'); // 2
        }

        document.write(x + ' <br>'); // 1
    }
</script>

That’s it !!! Hope I am clear on Block Scoped Variables & Block Scoped Functions. Do you find it useful? If yes, then please like and add comments :). Thank you and I will be happy to hear from you 🙂 🙂 .

Note :- Check here for Browser support details.

Advertisements

3 thoughts on “Javascript : Block Scoped Variables & Functions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s