Arrow functionss are a function shorthand using the => syntax (fat arrow). They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript. They support both expression and statement bodies. Unlike functions, arrows share the same lexical this as their surrounding code.
Scope
The lexical scope (this) in arrow is same as surrounding scope, unlike functions which create new scope.
Let's look at a function that takes an argument written in ES5
:
var sayHello = function (name) {
return 'Hello, ' + name + '!';
}
console.log(sayHello('Sean')); // Hello, Sean!
Nopw let's look at how this can be written in ES6
using an array function:
let sayHello = name => 'Hello, ' + name + '!';
console.log(sayHello('Sean'));
This may look bit confusing at the first glance, so let me explain it more clearly to you.
function(arguments) { espression }
Is analogous to:
arguments=>expression
So all we are really doing is removing some superfluous syntax.
Arguements
Our greeting function only accepts one argument, and when you only have one argument, parentheses are optional. Parentheses are required if you are handling more than one argument, though:
let sayHello = (firstName, lastName) => 'Hello, ' + firstname + lastName;
console.log(sayHello('Sean', 'A')); // Hello Sean A
Here is what an arrow function looks like with no arguments:
let sayHello = () => 'Hello, world!';
console.log(sayHello()); // Hello world!
Anonymous
Arrow functions are always anonymous, which means we can't do this with ES6:
function doSomething() {
...
}
Instead of this, we could assign our anonymous arrow function to a variable:
var doSomething = () => {
...
}
Scope
Arrow functions are not just syntactic sugar. They also change how scope
is handled in JavaScript. That means when every time you create a new function, it gets it's own scope.
var timer = function () {
var self = this;
this.seconds = 0;
setInterval(function () {
self.seconds++;
}, 1000);
}
We need to store the parent's this
so we need to store the parent's this in a local variable that we can then reference in the callback. Arrow functions inherit the current this value, so you no longer need to create a copy of your own:
var timer = function () {
this.seconds = 0;
setInterval(() => this.seconds++, 1000);
}
Syntax
So the syntax for arrow funcion's construct looks as follows:
// example 1
([param] [, param]) => {
statements
}
// example 2
param => expression
Which is the equivalent ES5 of:
// example 1
function ([param] [, param]) {
statements
}
// example 2
function (param) {
return expression
}