Wednesday, April 30, 2014

ECMAScript 6 - What's new in JavaScript - part 3 - let

Like I mentioned here: http://frontenddevs.blogspot.com/2013/09/ecmascript-6-whats-new-in-javascript.html I preparing series of posts about coming ECMAScript version 6.



Today I will write about let.


Let keyword.

Let's start from definition of what let is:

let allows you to declare variables, limiting its scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Basically it's work like var keyword for global scope and function scope BUT there is difference in block scope. Here are two examples. First one with var keyword:

console.log("foo", foo);
if(true){
  var foo = 'foo';
  console.log("foo", foo);
}
console.log("foo", foo);

In console we will receive 'undefined' then 'foo' and next 'foo'. What if will use let instead of var in similar example:

console.log("bar", bar);
if(true){
  let bar = 'bar';
  console.log("bar", bar);
}
console.log("bar", bar);
But now instead of undefined result for first console.log() we will get error:
ReferenceError: bar is not defined

This is the main difference between var and let keywords. For block scope (if, for, while loops) if you put var declaration inside it will be hoisted on top of the function scope.

That's why in first example we see 'undefined' for first console.log(). In second example let declaration is also hoisted but only on top of block scope (in this example on top of if loop scope).

Real life usage.


You should probably meet problem with for iteration inside which you add events click for each button:
for (var i = 0; i <= 10; i++) {
  var btn = document.createElement('button');
  btn.textContent = "Element with number " + i;
  btn.addEventListener('click', function(){
    console.log("button number is:", i);
  })

  document.body.appendChild(btn);
  document.body.appendChild(document.createElement('br'));

};

But what's happen when you click on any of buttons? You will get message in console "button number is: 10" for every click.

To prevent this you can wrap this into function where pass i parameter but instead of this you can use new learned let keyword:

for (var i = 0; i < 10; i++) {
  var btn = document.createElement('button');
  btn.textContent = "Another element with number " + i;
  let j = i;
  btn.addEventListener('click', function(){
    console.log("button number is:", j);
  })

  document.body.appendChild(btn);
  document.body.appendChild(document.createElement('br'));

};

If you learn something new by this post click on + in comments bellow and wait for next article from ES6 series.

Sources


All examples you can find on mine gist: 

No comments :

Post a Comment