menu
phone

(02) 8006 0506

ES6 Arrow Functions

The recent ECMAScript release (ES6) contains a number of new enhancements which further extend the Javascript language. One of our favourite parts of the ES6 experience, is the lambda / arrow function. Traditionally, in Javascript, you would write a function expression as follows:

function(param) {
   // Do Something Cool
};

Using ES6 Arrow Functions, this code snippet can be written slightly less verbosely, as follows:

(param) => {
   // Do Something Cool
};

The real power of these lambda functions however, is in the way in which they work in an object-oriented fashion, by lexically binding the this keyword. This becomes really powerful when using a framework which component-ises the application, as the this keyword becomes a fundamental aspect of software design. Traditionally such binding could be performed explicity using the bind keyword as follows:

function(param) {
   console.log(this);
}, bind(this);

Or using the following variable scope hack:

var _this = this;
function(param) {
   console.log(_this);
};

But with ES6 and the lexical binding of this within the body of an arrow / lambda function, it can be accessed with no additional code or hacks:

(param) => {
   console.log(this);
};

Stay tuned for more ES6 hints and tips, and for more information about what we are working on and developing!

Joe Logan

Feb 14 2017