Arrow function on ES6

In ES6 Arrow function is a short way to write a function, but is more than that.


var func = (x, y) => { return x + y; };

(param1, param2, …, paramN) => { statements }

On the left side the parameters, on the right side the statement or expression.

A simple example:


var func = (x, y) => { return x + y; };

With no paremeters:


() => { statements }

Return is implied if using an expression after an arrow.:


var arr = [5, 6, 13, 0, 1, 18, 23];

//normal
var sum = arr.reduce(function(a, b){ return a + b; });

//Arrow
var sum = arr.reduce((a, b) => a + b);

An arrow function does not create its own this context, so this has its original meaning from the enclosing context.


function Person(){
  this.age = 0;

  setInterval(() => {
  this.age++; // |this| properly refers to the person object
}

Leave a comment

Create a website or blog at WordPress.com

Up ↑