ES6 Arrow Functions Will Make You Happy

Why JavaScript ES6 Arrow Functions Will Make You Happy

In this post, I’ll be explaining the exciting changes coming to JavaScript with ES6 arrow functions. After reading this post, you will have a solid understanding of ES6 arrow functions. You will be able to write functions using the new syntax. You will be able to explain its new features to your friends and colleagues. The best part is it should only take you a few minutes.

There’s plenty to happy about!

Arrow Function Expression

The first thing you will notice about ES6 arrow functions is the new syntax. The ES6 arrow function expression syntax is shorter than the current function expression. That is great news to any JavaScript engineer. You get to cut down on characters and file size without taking away from code readability.

Note: You may see some people refer to them as fat arrow functions.

Syntax


// Multiple statements
([param] [,param]) => {
statements
}
// Single expression
param => expression
/* _____ Examples _____ */
// No arguments, must use ()
var noArgs = () => {
// Do something
};
// Only one argument, () and {} are optional
var oneArg = param1 => // Do something with param1
// Multiple arguments, must use ()
var multiArgs = ( param1, param2, param3 /* … */ ) => {
// Do something with param1, param2, param3 and so on
};

view raw

gistfile1.js

hosted with ❤ by GitHub

1, 2, 3 Arrow Function

ES6 Arrow Functions as easy as 1, 2, 3

You may find it helpful to break the process required to create an arrow function up into three steps:

1. Provide the parameters


var func = ( x, y )

view raw

gistfile1.js

hosted with ❤ by GitHub

2. Add in that fat arrow goodness


var func = ( x, y ) =>

view raw

gistfile1.js

hosted with ❤ by GitHub

3. Define the body of the function


var func = ( x, y ) => x + y;

view raw

gistfile1.js

hosted with ❤ by GitHub

Lambdas!

One of the key things to note is that when you only use one argument the function returns the result implicitly. You don’t have to use the return keyword. This is quite handy for lots of scenarios. Other programming languages refer to this style as lambdas.


var square = number => number * number;
console.log( square( 5 ) ); // 25

view raw

gistfile1.js

hosted with ❤ by GitHub

In the above code, the result of number * number is automatically returned. So you will see 25 in your console. I have some ideas of how you can put this to use in JavaScript. I may write a more detailed post on lambdas at some point in the future. Make sure and let me know in the comments if you’d find that useful.

Lexical this Binding

In earlier versions of JavaScript, the context of this was dynamic. Every new function defined its own this value. In ES6, this is lexically bound. Simply put, it retains a reference to the enclosing context. I’ll give you some examples so you can understand the full benefit of a lexical this. Say you wanted to create a Gamer class to track play time for a game you’re making.

In ES5, you might try writing the following code:


function Gamer() {
// 'this' refers to Gamer
this.playTime = 0;
// We think trackPlayTime() will update a gamer's playtime every second
setInterval( function trackPlayTime() {
// But we're wrong because trackPlayTime() creates it's own version of 'this'
this.playTime++;
// Outputs NaN, because this.playTime was never cast as an integer in this scope
console.log( this.playTime );
}, 1000 );
// Outputs 0, because this.playTime was never incremented in this scope
console.log( this.playTime );
}
var gamer = new Gamer();

view raw

gistfile1.js

hosted with ❤ by GitHub

A typical solution for handling the problem in the current version of JavaScript would be to do something like:


function Gamer() {
// Store value of this in a variable
var self = this; // Some people use that or _this
self.playTime = 0;
// trackPlayTime() will now correctly auto increment every second
setInterval( function trackPlayTime() {
// Because we're using a variable we don't have to worry about the dynamic value of this in the new function scope
self.playTime++;
// Correctly out
console.log( self.playTime );
}, 1000 );
}
var gamer = new Gamer();

view raw

gistfile1.js

hosted with ❤ by GitHub

With ES6 arrow functions, this refers to the enclosing context. So you can use:


function Gamer() {
// 'this' refers to Gamer
this.playTime = 0;
// We use an ES6 arrow function
setInterval(() => {
// So 'this' still refers to the Gamer object
this.playTime++;
// Correctly outputs and incremented value representing play time in seconds
console.log( this.playTime );
}, 1000 );
}
var gamer = new Gamer();

view raw

gistfile1.js

hosted with ❤ by GitHub

Conclusion

Well, that is a quick overview of ES6 arrow functions. I hope you feel like you’ve leveled up your ES6 knowledge. You should be ready to begin taking on ES6 arrow functions.

You should spend some time practicing what you’ve learned. If you haven’t already, make sure to check out my post, You Need To Know That ES6 Has Arrived. It will get you motivated to start putting your ES6 knowledge to use now.

If you’ve found this post helpful, please make sure and leave a comment. Let me know how I’m doing. It helps me a lot.


Comments

Leave a Reply

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