let keyword in Javascript ES6

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Javascript E6 introduced the “let” keyword that works similar to the “var” keyword in defining new variables.  The difference is that “let” uses block scoping.   Consider this example, where we first just use “let” in place of where we normally use “var”…

let keyword

Nothing special here.  It works as expected with the “adder” function returning 15 to be displayed in the browser.   Note how we have defined a temporary variable “numberToAdd” using the “var” keyword inside the for loop.  This variable still persists outside of the for loop, as evidenced by console.log() statement which works perfectly fine.

However, if instead we defined it with the “let” keyword …

block scoping

The program would throw an Uncaught ReferenceError saying that “numberToAdd” on line 18 outside of the for-loop does not exists.  That is block scoping.  Because “numberToAdd” is defined with “let” inside the for-block, it only exists inside that for-block.

Similarly the “i” in “let i in numbers” only exists inside the for-block.

More ES6 features here.

 


Related Posts

Tags

Share This