DEV Community

Mohana Naga Venkat Sayempu
Mohana Naga Venkat Sayempu

Posted on

5 1

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post