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.

Dive into Javascript forEach()

Hello everyone, this time lets go through one of the popular control flow statement in programming language named as “foreach”. “foreach”, as the name suggests, it is a control flow statement for traversing items in one or set of collection(s). This article will cover how it works with Javascript.

I hope everybody reading this article knows about what control flow statement is. Still lets go through a short glimpse about it.

“The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping and branching, enabling your program to conditionally execute particular blocks of code.”

It suggests flow of the control, the order in which the statements will execute in any application. Some examples are switch-case, if, if-else (decision-making statements), for, while, do-while (looping statements), return, break, continue, label (branching statements), in general.

We will go through one new control flow statement called foreach, which is supported by these languages, as per the wiki.

General Syntax :-

for each item in collection:
  do something to item

forEach in Javascript, iterates upon Array or object(Map or Set) with the following syntax.

  • Array.prototype.forEach() :- arrElem.forEach(callback[, args]);
  • Map.prototype.forEach() :- arrElem.forEach(callback[, args]);
  • Set.prototype.forEach() :- arrElem.forEach(callback[, args]);

1. Array.prototype.forEach() :-
The method executes the specified callback function once for every array element. Lets check some examples and get clarified.

Example 1 :-

var arr = [1, 2, 3, 4, 5];
arr.forEach(function(val) {
    document.write(val + ' - ');
});

O/P :- 1 – 2 – 3 – 4 – 5

Example 2 :-

function getSquare(elem) {
    document.write((elem * elem) + ' - ');
}

var arr = [1, 2, 3, 4, 5];
arr.forEach(getSquare);

O/P :- 1 – 4 – 9 – 16 – 25

Example 3 :-

// Object which contains the callback function for forEach.
var testObj = {
    getSquare: function(elem) {
        document.write((elem * elem) + ' - ');
    }
};

var arr = [1, 2, 3, 4, 5];

// First argument is to call the getSquare function.
// Second argument 'testObj' is 'this value' present inside callback function.
arr.forEach(testObj.getSquare, testObj);

O/P :- 1 – 4 – 9 – 16 – 25

2. Map.prototype.forEach() :-
The method executes the specified callback function once per each key/value pair in the Map object. Lets go through the examples.

The syntax for callback function should be like below :-

Syntax :-

function callbackfn(value, key, obj)

// As per ECMAScript
function callbackfn(value: V, index: K, map: Map)

Example 1 :-

function assignVehicle(val, key, mapObj) {
    document.write('&lt;b&gt;' + key + '&lt;/b&gt; has bought a new &lt;b&gt;'+ val + '&lt;/b&gt;&lt;br&gt;');
}

var map = new Map();
map.set('prava', 'Fiat');
map.set('Bob', 'Harley');
map.set('Maria', 'Audi');

map.forEach(assignVehicle);

O/P :-
prava has bought a new Fiat
Bob has bought a new Harley
Maria has bought a new Audi

3. Set.prototype.forEach() :-
The method executes the specified callback function in the Set object once per each value. Lets check some example.

Example 1 :-

function checkValue(val) {
    document.write(val + ' - ');
}

var setObj = new Set();
setObj.add(1);
setObj.add(2);
setObj.add('prava');
setObj.add('Maria');

setObj.forEach(checkValue);

O/P :- 1 – 2 – prava – Maria

That’s it !!! We are done with the forEach statement of Javascript. Hope you are clear on the use of forEach control statement and hope you get to know how to use it. But even though it is pretty to use and upon using, the code looks much cleaner, there are some disadvantages of using forEach, which I will cover in my upcoming blog. So, stay tuned for more details and what to use & what not.

Do you find it useful? If yes, then please like and add some comments :). Thank you and I will be happy to hear from you 🙂 :).