loading...

Arrow Functions

mohananagavenkat profile image Mohana Naga Venkat Sayempu ・1 min read

es6 (9 Part Series)

1) let and const in javascript 2) Arrow Functions 3 ... 7 3) ES6 Modules 4) Template Strings 5) Object Literal Enhancements 6) Destructuring 7) Spread Operator 8) Symbols 9) Iterators

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 😃 .

es6 (9 Part Series)

1) let and const in javascript 2) Arrow Functions 3 ... 7 3) ES6 Modules 4) Template Strings 5) Object Literal Enhancements 6) Destructuring 7) Spread Operator 8) Symbols 9) Iterators

Posted on May 25 by:

mohananagavenkat profile

Mohana Naga Venkat Sayempu

@mohananagavenkat

Full-Stack Developer. In a relationship with web 😁. Worked for startup companies. Apart from that, I am a good Badminton Player.

Discussion

markdown guide