let in Javacript ES-6

Code for this and several other ES-6 features can be found in my github

In ES-5 there was only one keyword to declare a variable. The var keyword. The variables declared using the var keyword have function scope. That is, if a variable is declared with in a function, another variable with same name is declared inside a block, the variable declared inside the block overrides the function variable.
For example in the following code:

var scope = function() {    
var int = 10;    
if(int 
Two variables with the same name
int
are declared with in the
scope
function. One is declared at the function level, and another is declared inside the
if
block. In languages like Java, we will expect both these variables to operate in different scopes. However, all variables declared with the
var
keyword, have function scope. Which means, the second
int
will override the first
int
. Hence the output of this program will be as follows:

int value from inside 11
int value from outside 11
The only way to bring in block scope in javascript was to create a new scope with in the block by creating an self invoking function as follows:

var scope = function() {    
var int = 10;    
if(int 
In this case, since
 int value from inside 
is executed from within another function, it gets a different scope and it does not affect or get affected by the
int
variable outside the block. However, this is very verbose. In order to make it easier to declare block scopes, in ES-6 the

let 
keyword is introduced. ES-6 example:

var scope = function() {    
var int = 10;    
if(int 
Since the
int
variable inside the block is declared using

let
keyword, the variable outside does not affect the variable inside.

Comments

Popular posts from this blog

Docker Commands

Dockerfile

ES-6 classes