Wednesday, 3 August 2016

Blocks and Closures

One of the less exciting features added to ES6 are blocks. You can put sections of code between brackets anywhere in your code and the variables declared there with let will be local to that section. I think Perl has something similar, but honestly I don't see much use to it.
Reading the section From IIFEs to blocks in this nice write up has made me see that in the end they can be useful. The sample there is not complete, so I'll drop one here. We use IIFEs many times to create closures, so with blocks we can move from this:

 var printAndCount = function(){
  var counter = 0;
  return function(){
   console.log("execution: " + counter++);
  }
 }();
        printAndCount();

to this

 {
  let counter = 0;
  var printAndCount = function(){
   console.log("execution: " + counter++);
  }
 }
        printAndCount();

The latter is shorter, but the former has much more freak appeal :-)

No comments:

Post a Comment