Arrow functions
// Arrow functions are anonymous
// ES6
([param] [, param]) => {
statements
}
// ES5
function ([param] [, param]) {
statements
}
// ES6
param => expression
// ES5
function (param) {
return expression
}
// To name an arrow function anyway
// ES6:
var doSomething = () => {
//...
}
// example 1:
// ES5
var numbers = [1,2,3,4,5];
var timesTwo = numbers.map(function (number) {
return number * 2;
});
// ES6
var numbers = [1,2,3,4,5];
var timesTwo = numbers.map((number) => number * 2);
console.log(timesTwo); // [2, 4, 6, 8, 10]
console.log(timesTwo); // [2, 4, 6, 8, 10]
// example 2:
// ES5
function FooCtrl (FooService) {
var that = this;
that.foo = 'Hello';
FooService
.doSomething(function (response) {
that.foo = response;
});
}
// ES6
function FooCtrl (FooService) {
this.foo = 'Hello';
FooService
.doSomething((response) => { // woo, pretty
this.foo = response;
});
}
// ES6: even better
function FooCtrl (FooService) {
this.foo = 'Hello';
FooService
.doSomething((response) => this.foo = response);
}