DEV Community

Mohana Naga Venkat Sayempu
Mohana Naga Venkat Sayempu

Posted on

Arrow Functions

Note: This is part of my es6 series of posts.

Arrow functions are a concise anonymous function syntax, and their this value is lexically bound to their enclosing scope. (Where the function was defined)

Single Expression

When the arrow function body is a single expression it is implicitly returned.

var add = (a,b) => a+b;

Single Argument

When the arrow function has only one argument the parens around the parameters can be omitted.

var odd = n => n % 2;

No Arguments

When the arrow function has no arguments you need an empty parens ().

var random = () => Math.random();

Multiple Expressions

When the arrow function body has multiple expressions then they must be wrapped in {} and the return statement may not be omitted.

var shout = s => {
  s = s.toUpperCase();
  s = s + '!';
  return s;

Lexical this

The arrow function's this value is bound to the enclosing scope, so no more need for var self = this.

function Counter () {
  this.count = 0;
  setInterval(() => this.count++, 1000);

var counter = new Counter();

Concise Functional Iteration

Arrow functions can be used to write iteration, map, reduce and filter operations quite concisely.

var data = ['one', 'two', 'three'];
var processed = data
  .map(s => s.length)
  .filter(length => length < 5);

Happy coding πŸ˜ƒ .

Top comments (0)