let declarations

let Declarations – Understanding ES6

No TL;DR Required 🙂

I recently got back from attending AngularU in San Francisco. One of the best parts about going to community conferences like this is getting fired up about programming. There was a lot of information that I soaked up while in SF. It also became very clear that there is a lot that I need to learn if I want to keep up with the front end development community. One of those things is Ecma Script 6, ES6, or ES 2015 (it’s being called a lot of things).

So I decided to write blog articles as I start learning different pieces of ES6. This is the first in a series and will be about let declarations.

First off, most of what I’m learning is from the free copy of ES6 & Beyond.

let Declarations

let is another way to declare a variable in ES6. Let’s go over some of the features and specs for let declarations.

Block Scope

When declaring a var in javascript it is confined to the scope of it’s enclosing function or globally if declared outside any function scopes. In ES6 we are introduced to block scope. There will be an entire post about this but the need-to-know with this is anything within a block {..} has a scope confined to that block. let declarations adhear to this block scope and cannot be accessed outside of their block scope. For example the following code example would not work:

1
2
3
4
{
  let foo = "bar"
}
console.log(foo);

The error foo is not defined would be returned becasue the console.log is being called outside the scope where foo was declared.

No Hoisting

It is also a good idea to put all let declarations at the top of the block. For example the following code would also return foo is not defined

1
2
3
console.log(foo);

let foo = "bar"

This is different behavior than what we see with var declarations. Variables declared with var are “hoisted” to the top of the scope so that they are initiated immediately and will return undefined until they are set to a value.

Let In for Loops

You can also notice unique behavior of let declarations when initializing them in the header of for loops. The following example is taken from ES6 & Beyond.

1
2
3
4
5
6
7
8
9
var funcs = [];

for (let i = 0; i < 5; i++) {
    funcs.push( function(){
        console.log( i );
    } );
}

funcs[3]();     // 3

If you were to right the same code with a var rather than a let declaration the function would return 5. This is because a new i is declared for each iteration of the for loop and a reference to that instance of the let is kept.

Pro Tip: Play with ES6

Take advantage of the tools out there to play around with ES6 and practice your new skills.

ES6 Fiddle

Babel Playground

Leave a Reply

Your email address will not be published. Required fields are marked *