All about ES6 fat arrows (=>)
ES6 contains many nice little features. Fat arrows are perhaps one of the most surprising, and once you understand them, one of the most enjoyable.
Fat arrows give us a new, shorthand syntax for defining functions, and also a new way to initialise the this
variable that comes into existence whenever a function is called.
Definition
We define a JavaScript function like this:
function() {}
An equivalent fat arrow function looks like this:
() => {}
A real example might look like this:
function (a,b) {
console.log(a+b);
};
which would become
(a,b) => {console.log(a+b)};
Exercise - Fat Fingers
Have a play with the above example at the babel repl here.
Convert the following into fat arrow format:
var sayHello = function() {
console.log('hello')
}
sayHello();
Do the same with this self executing function:
(function() {
var greeting = 'hello';
console.log(greeting);
})();
Exactly one parameter
If our function has exactly one parameter, we can skip the braces on the left hand side. Our function then looks like this:
a => {return a + 1}
This is equivalent to:
function(a) {
return a + 1;
}
Exercise - One Parameter
Have a play with the above example at the babel repl here.
Convert the following into fat arrow format:
var sayHello = function(name) {
return "Hello " + name;
}
Concise syntax
As if this wasn't short enough, We have a concise syntax. If our fuction contains exactly one line, we can also omit the curly braces and return statement, like so:
a => a + 1
which again is equivalent to:
function(a) {
return a + 1;
}
The evaluated value of the function expression is returned automatically. we don't need the return statement.
These sorts of functions are perfect for passing around, and this makes functional programming incredibly easy.
var i = 0;
setInterval( () => {i++}, 500 )
:markdown