- ES6 provides the true block scope binding using Let keyword.
- let allows us to declare variables that are limited in scope to the block, statement, or expression on which it is used.
- variable declared in var keyword are global or local to an entire function regardless of block scope.
- In this demo, “We will learn to use true block scope binding using let keyword”.
- We are using the same project that we have used in my previous post.
- The following code has 2 different method printIUsingVar() and printIUsingLet().In printIUsingVar() the variable i is declared in a for loop using var keyword.In printIUsingLet() method variable i is declared in a for loop using let keyword.The for loop in both the methods just adds 1 to value i.In both the method a console log used to print the value of i.The console log message in printIUsingVar() method will print 5 as i is defined using var keyword and i is available to function scope.The console log message in printIUsingLet() method will throw an error i is not defined.
var printIUsingVar = function(){ //variable i is avaialable to function scope for (var i = 1; i < 5; i++) { i = i+1; } //i will have value 5, as i is declared using var console.log("i: ",i); }; var printIUsingLet = function(){ //variable i is binded to for loop scope for (let i = 1; i < 5; i++) { i = i+1; } //i is udefined, as i is binded to local scope using let console.log("i: ",i); }; console.log(printIUsingVar()); console.log(printIUsingLet());
- The Grunt Traceur watcher will detect the changes and generates the normal JavaScript.The following screenshot shows the terminal with Grunt watcher detecting changes.
- The generated compiled code by Traceur Grunt watcher is listed below:
"use strict"; var __moduleName = (void 0); var printIUsingVar = function() { for (var i = 1; i < 5; i++) { i = i + 1; } console.log("i: ", i); }; var printIUsingLet = function() { { try { throw undefined; } catch ($i) { $i = 1; for (; $i < 5; $i++) { try { throw undefined; } catch (i) { i = $i; try { i = i + 1; } finally { $i = i; } } } } } console.log("i: ", i); }; console.log(printIUsingVar()); console.log(printIUsingLet());
- The output of the above code is shown in below screenshot with a chrome console.