Hope you are excited and ready to explore the first feature of the language in this series. In this session of the series we are understanding more on the scope and variable bindings in the scope.
Yes quite strange, variables declared with keyword var are of functional scope, contrast to most of programming languages variables scope is confined to block.
Following code snippet is demos the fact of functional scope of variables defined by keyword var.
To overcome above shortfall ECMAScript 6 brought 2 keywords to declare variable ‘let’ and ‘const’. Do experiment with above code examples declaring variable with ‘let’ and ‘const’ for get more insight on the concept.
Difference between ‘let’ and ‘const’
Both const and let are similar to var but their scope is within the block. And they never allow redefine the variable within the scope.
const is similar to const keyword ofC++ , where it is read only and has to be initialized when we declare it.
Avoid IIFEs (immediately-invoked function expressions)
With using block scoping variable ‘let’ we can avoid this.
We might expect with above code it will iterate over 10 times from 0,1,…,9. If you try to run on your local setup that's not the real story!!!. Since variable i is functional scope its existence is present even outside the for loop. And within the for loop it holds the value 10 and print 10 ten times!!!.
So with IIFE we can overcome this shortfall and that’s what we had option prior to ECMAScript 6. Below code is IIFE implementation of the above requirement. With the below implementation code iterates over 10 times from 0,1,…,9.
But solution doesn’t looks elegant where we make use of anonymous function expression to prevent leaking of local variables to global scope. With ECMAScript we can achieve this elegantly by following code.
To summarize this part of tutorial we spent time on understanding the functional scope of the var keyword and got introduced with let and const keyword. We explored the IIFE pattern in brief and achieved same thing with use of let keyword of ECMAScript 6.
In this part we didn’t pay much attention on ‘const’ keyword, as I has separate plan to cover it on while discussing its behavior with for-in and for-of loops. Hope you enjoyed, stay tuned for more on this series.