DEV Community

Cover image for What is an Arrow Function?
Erin Ponsonby
Erin Ponsonby

Posted on

What is an Arrow Function?

For my final Flatiron School project, I ended up making use of the arrow function. This turned out to be a great opportunity to really dive into their benefits and how they work.

Syntactic Sugar

In short, an arrow function is simply a syntactically compact way of writing a regular function expression. Here’s an example:

const flavors = [
   "Cookie Dough",
   "Strawberry",
   "Mint Chocolate Chip"
];

console.log(flavors.map(flavor => flavor.length));
// logs [12, 10, 19]

The Arrow Function and "This"

An important difference between a regular function expression and an arrow function has to do with the this keyword.

In a regular function expression, the value of this is defined based on how the function is called.

  • In the case of a constructor, the value of this is an instance of the new object
  • If the function is called as an object method (i.e. object.myFunc()), the value of this is the base object

Arrow functions do not have their own this. Instead, the this value of the enclosing lexical scope is used.

Wait, What is Lexical Scope?

As a quick aside, let's review what we mean by lexical scope.

function helloName() {
  let name = "Erin"

  function printName() {
     console.log(name)
  }

  printName()
}

helloName()
// logs "Erin"

In the above example, even though the variable name is defined in the outer function, the value of name will be logged by the inner function when helloName is called. This is because nested functions (printName(), in this case) have access to variables declared in their outer scope.

An Example

Here's an example of how the value of this changes with arrow functions.

function Dog() {
   this.name = "Pupper"

   setInterval(() => {
      console.log(this.name)
   }, 1000)
}

Dog()
// logs "Pupper" at one second intervals

Because we used an arrow function with setInterval, the value of this from the outer function is used.

Sources:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Top comments (0)