The KIRUPA orange logo! A stylized orange made to look like a glass of orange juice! Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

TL;DR: Arrow Functions

by StackOverflow Contributors   |   22 October 2017

This TL;DR content was ported over from Stack Overflow Documentation, now retired. To access the source and attribution please access the Docs archive and reference topic ID: 5007. Some of the contributors to this content are armfoot, SZenC, ndugger, TheGenie OfTruth, Ethan, Christian, Nhan, and others. Please visit the archive for the full list of contributors.

In JavaScript, functions may be anonymously defined using the "arrow" (=>) syntax, which is sometimes referred to as a lambda expression. The simplest form of an arrow function has its arguments on the left side of => and the return value on the right side:

item => item + 1 // -> function(item){return item + 1}

This function can be immediately invoked by providing an argument to the expression:

(item => item + 1)(41) // -> 42

If an arrow function takes a single parameter, the parentheses around that parameter are optional. For example, the following expressions assign the same type of function into constant variables:

const foo = bar => bar + 1;
const bar = (baz) => baz + 1;

However, if the arrow function takes no parameters, or more than one parameter, a new set of parentheses must encase all the arguments:

(() => "foo")() // -> "foo"

((bow, arrow) => bow + arrow)('I took an arrow ', 'to the knee...')
// -> "I took an arrow to the knee..."

If the function body doesn't consist of a single expression, it must be surrounded by brackets and use an explicit return statement for providing a result:

(bar => {
  const baz = 41;
  return bar + baz;
})(1); // -> 42

If the arrow function's body consists only of an object literal, this object literal has to be enclosed in parentheses:

(bar => ({ baz: 1 }))(); // -> Object {baz: 1}

The extra parentheses indicate that the opening and closing brackets are part of the object literal, i.e. they are not delimiters of the function body.

Lexical Scoping & Binding (Value of "this")

Arrow functions are lexically scoped; this means that their this Binding is bound to the context of the surrounding scope. That is to say, whatever this refers to can be preserved by using an arrow function.

Take a look at the following example. The class Cow has a method that allows for it to print out the sound it makes after 1 second:

class Cow {

  constructor() {
    this.sound = "moo";
  }

  makeSoundLater() {
    setTimeout(() => console.log(this.sound), 1000);
  }
}

const betsy = new Cow();
betsy.makeSoundLater();

In the makeSoundLater() method, the this context refers to the current instance of the Cow object, so in the case where I call betsy.makeSoundLater(), the this context refers to betsy.

By using the arrow function, I preserve the this context so that I can make reference to this.sound when it comes time to print it out, which will properly print out "moo".

Arguments Object

Arrow functions do not expose an arguments object; therefore, arguments would simply refer to a variable in the current scope:

const arguments = [true];
const foo = x => console.log(arguments[0]);

foo(false); // -> true

Due to this, arrow functions are also not aware of their caller/callee.

While the lack of an arguments object can be a limitation in some edge cases, rest parameters are generally a suitable alternative:

const arguments = [true];
const foo = (...arguments) => console.log(arguments[0]);

foo(false); // -> false

Implicit Return

Arrow functions may implicitly return values by simply omitting the curly braces that traditionally wrap a function's body if their body only contains a single expression.

const foo = x => x + 1;
foo(1); // -> 2

When using implicit returns, object literals must be wrapped in parenthesis so that the curly braces are not mistaken for the opening of the function's body:

const foo = () => { bar: 1 } // foo() returns undefined
const foo = () => ({ bar: 1 }) // foo() returns {bar: 1}

Conclusion

The information here is from the (now retired) Stack Overflow Documentation archive. The goal of this content is to provide you with quick access to information with very little of the narrative that long-form articles on this site cover. If you have a question about this or any other topic, the easiest thing is to drop by the forums where a bunch of the friendliest people you'll ever run into will be happy to help you out!

Stackoverflow Contributors

THE KIRUPA NEWSLETTER

Get cool tips, tricks, selfies, and more...personally hand-delivered to your inbox!

( View past issues for an idea of what you've been missing out on all this time! )

WHAT DO YOU THINK?

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends