Close

JavaScript - Arrow Functions

[Updated: Jul 10, 2018, Created: Jul 8, 2018]

ES6 (ECMAScript 2015) introduced following new syntax of writing functions:
Parameters => ConciseBody.

Before ES6:

var isEven = function (num) { return num % 2 == 0; }

In ES6:

var isEven = num => num % 2 == 0;

It is very similar to Java 8 lambda.

Examples

var run = () => console.log('hi there');
run();
var square = x => x * x;
console.log(square(5));

More than one parameters:

var sum = (a, b) => a + b;
console.log(sum(3, 8));

Object literal expression:

var rectangle = (w, h) => ({width:w, height:h, area:w*h});
console.log(rectangle(3,4));

Array Operations:

var nums = [2, 4, 7, 9];
var evens = nums.filter(n => n % 2 == 0)
console.log(evens);
var nums = [2, 4, 7, 9];
var squares = nums.map(n => n * n)
console.log(squares);
var nums = [2, 4, 7, 9];
var sum = nums.reduce( (a,b) => a + b)
console.log(sum);
var nums = [2, 4, 7, 9];
var sumOfSquaredEvens = nums.filter(n => n % 2 == 0)
                            .map(n => n * n)
                            .reduce( (a,b) => a + b)
console.log(sumOfSquaredEvens);

Non-binding of 'this'

Before ES6:

function Rectangle(){
 this.w = 10;
 this.h = 5;
 this.area = 0;
 setTimeout(function () {
     this.area = this.w * this.h;
     console.log(this.area);
  }, 100);
  }
new Rectangle();
NaN

In above example we are setting this.area for Rectangle after 100 millisecs via a timer. As seen in the output, a normal nested function cannot see this.w, this.h and this.area as the members of the enclosing object (Rectangle). In fact every new function defines its own 'this' value. In other words 'this' is bound lexically.

In ES6, an arrow function does not have its own 'this' but 'this' value of the enclosing execution context is used.

function Rectangle(){
 this.w = 10;
 this.h = 5;
 this.area = 0;
 setTimeout(() => {
     this.area = this.w * this.h;
     console.log(this.area);
  }, 100);
  }
new Rectangle();
50

See Also