CHAPTER 4
Arrows are a function shorthand using the => syntax. They are syntactically similar to the fat arrow syntax in C#, Java, and CoffeeScript. They support both expression bodies and statement block bodies that return the value of the expression. Unlike functions, arrows share the same lexical this as their surrounding code.
The following is what a classic function would look like maintaining the same lexical this:
Code Listing 70
var square = (function(num) { return num * num; }).bind(this); |
Now, we can simply write it as follows:
Code Listing: 71
let square = (num) => { return num * num; }; |
Expression bodies are a single line expression with the => token and an implied return value.
Code Listing: 72
let evens = [2, 4, 6, 8, 10]; let odds = evens.map(v => v + 1); let nums = evens.map((v, i) => v + i); console.log(odds); console.log(nums); |
Running the preceding code produces the following result:
Code Listing: 73
[3, 5, 7, 9, 11] [2, 5, 8, 11, 14] |
As you can see from the example, this new syntax is very clean and removes needless boilerplate code.
Statement bodies are multiline statements that allow for more complex logic. You also have the option to return a value from the statement or not.
Code Listing: 74
let fives = []; let nums = [1, 2, 5, 15, 25, 32]; nums.forEach(v => { if (v % 5 === 0) fives.push(v); }); console.log(fives); |
Running the preceding code produces the following result:
Code Listing: 75
[5, 15, 25] |
With this new fat arrow syntax, we can safely access the lexical this without worrying about it changing on us.
Let’s look at an example:
Code Listing: 76
let matt = { name: "Matt", friends: ["Mark", "Lyle", "Rian"], printFriends() { this.friends.forEach(f => console.log(this.name + " knows " + f)); } } matt.printFriends(); |
Running the preceding code produces the following result:
Code Listing: 77
Matt knows Mark Matt knows Lyle Matt knows Rian |
Previously, we would have had to create a separate _this closure variable to enable accessing the correct this. That actually is exactly what happens for us automatically when our code gets transpiled. Take a look at the same code snippet after it has been transpiled to ES5:
Code Listing: 78
"use strict"; var matt = { name: "Matt", friends: ["Mark", "Lyle", "Rian"], printFriends: function printFriends() { var _this = this; this.friends.forEach(function (f) { return console.log(_this.name + " knows " + f); }); } }; matt.printFriends(); |
As you can see, a new variable _this was created for us within the forEach function.