ES6 Lambda Expressions

This is the part of a series of blogs on the new features on the upcoming ECMAScript 6 (ES6) specification which JavaScript implements.

In this blog we focus on the lambda expressions, also called arrow functions, introduced in ES6.

Lambda Expression #

Lambda expressions are also known as anonymous functions, function literals, or lambda abstractions. In a high level sense, lambda expressions are often passed as arguments to higher-order functions. Higher-order functions are functions that take one or more functions as an input, or functions that output another function. This allows the nesting of anonymous functions to be intuitive for the developer by “[allowing] access to variables in the scope of the containing function (non-local variables)”. JavaScript accomplishes this using closures.

ES6 Syntax #

Developers who have used CoffeeScript would not be frazzled by this “new” ES6 syntax as it is very similar to what CoffeeScript offers.

Simple example

ES5

var x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
x.map(function(x) {
    console.log(x);
});

ES6

let x = [0, 1, 2, ..., 10];
x.map(x => console.log(x)); // (args) => {}

The main gotcha for CoffeeScript users is to remember ES6 only has the fat arrow not the normal arrow. The fat arrow or => bounds the this scope into the lambda expression in ES6 (as in CoffeeScript).

Lexical this example

ES5

function() {
    var that = this;
    that.i = 0;
    setInterval(function() {
        // we have a different this scope in this function so we use closure to get the variable that
        console.log(++that.i);
    }, 1000);
}

ES6

function() {
    this.i = 0;
    setInterval(() => {
        console.log(++this.i);
    }, 1000);
}

Use Case #

Without a doubt, arrow functions in ES6 allows developers to remove a lot of the ceremony work that makes understanding JS this scoping hard for beginners as well as code readability. Will this, however, make new devs blissfully ignorant of how this scoping works? Maybe.

The main uses for the fat arrow functions would likely be for list processing such as map, filter, reduce, etc. or for the times when you want to correct this in an anonymous function such as inside a setTimeout.

The wrong uses for lambda expressions are when you need to do a new or you use apply, call, or bind as this won’t change this in the fat arrow functions.

 
261
Kudos
 
261
Kudos

Now read this

LRU Cache in JavaScript

This is an LRU (least recently used) cache implementation in JavaScript. It’s very efficient and uses two data structures to manage the elements. A doubly-linked list and a map gives us the following: Time complexity: O(1) Space... Continue →