Click here to Skip to main content
15,884,836 members
Articles / Programming Languages / Javascript

JavaScript: Block Scoped Variables & Functions

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
7 Sep 2016CPOL3 min read 10.5K   5   1
This article highlights new feature called Block Scoped Variable and Block Scoped Functions.

This article highlights new feature introduced in ECMAScript 6 called “Block Scoped Variable” & “Block Scoped Functions“. On the internet, you may find many articles on block scoped variable and functions. But this is an attempt to present the topic in the 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 let's dive into this concept quickly without wasting much time.

Block Scoped Variables

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

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

Example 1 (with VAR Keyword)

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

    document.write(i);
</script>

// Output : 10

Example 1 (with LET Keyword)

JavaScript
<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
<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 the code below.

Example 2 (with LET Keyword)

HTML
<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. Let's go through one example to differentiate.

Example 3 (Syntax with ES5)

JavaScript
<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 the same method but in a 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, let's see how the scoped definition for function changed.

Example 3 (Syntax with ES6)

JavaScript
<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 do not need to write a complicated line like this (function() { .. })();. We only have to write { .. };, plain & simple.
  2. We do not need to use var = function (param1, param2, …) { … };, instead we can directly write function (param1, param2, …) { … }.

Example 4 (Syntax with ES5)

JavaScript
<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)

JavaScript
<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. Did 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Software engineer with around 6 years of web application development experience in open source technologies like PHP, MySQL, HTML, HTML5, CSS, CSS3, Javascript, jQuery etc.

I love to learn and share my knowledge in which manner I can and like to solve the issues as in the coding perspective. I am an active contributor in community forums like StackOverflow, CodeProject etc. Besides that, I write blogs in free time and speak in various technical community events.

Comments and Discussions

 
PraiseWell written. Useful article Pin
Suvendu Shekhar Giri7-Sep-16 20:29
professionalSuvendu Shekhar Giri7-Sep-16 20:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.