Arrow Function
The arrow function (=>) is a shorthand syntax for an anonymous function.
param => statements or expression
Let’s explicate this a bit more:
param
—The name of an argument or arguments. If the function has zero arguments, this needs to be indicated with (). For only one argument the parentheses are not required.
statements or expression
—Multiple statements need to be enclosed in curly braces. A single expression, though, doesn’t need braces. The expression is also the return value of that function.
var overTen = x => x > 10 ? 10 : x; overTen(8); // returns 8 overTen(12); // returns 10
Note that the function keyword isn’t required, and that the parentheses can be omitted since there is a single argument. The following example has two arguments:
var higher = (x, y) => { if (x > y) { return x; } else { return y; } } higher(7, 9); // returns 9 higher(12, 3); // returns 12
As well as being a little simpler to write, arrow functions also have the feature that they inherit the value of this from the container. This is really handy when using objects. Previously we needed to assign this to a variable to pass it into a function:
function myObject() { this.height = 13; var self = this; setTimeout(function fiveSecondsLater() { console.log(self.height); }, 5000) } var o = new myObject();
In the preceding example, we couldn’t simply use
console.log(this.height);
because this would refer to its immediate container, here the function fiveSecondsLater(). However, by using arrow functions the use of a variable like self can be avoided:
function myObject() { this.height = 13; setTimeout(() => { console.log(this.height); // 'this' here refers to myObject }, 5000) } var o = new myObject();