Skip to content
Arif Mulani Sans Arif
Tags Search
Go back

Arrow function expressions

In last two articles, we have covered the this keyword and polyfills for call, apply, and bind. I still believe polyfills is the crazy part of JavaScript till now. In this article, we will dive into arrow function expressions.

An arrow function expression is a compact alternative to a traditional function expression, with some semantic differences and deliberate limitations in usage.

  • Arrow functions don’t have their own bindings to this, arguments, or super and should not be used as methods.
  • Arrow functions cannot be used as constructors. Calling them with new throws a TypeError. They also don’t have access to the new.target keyword.
  • Arrow functions cannot use yield within their body and cannot created as generator functions.

Let’s skip the syntax. It’s pretty simple. In what case you should wrap your parameters in parathesis and when you can skip them. You can return implicitly if you have single expression, in case of object literal, you need to wrap it in parathesis. You can read more about the syntax here.

Behavior and limitations

No this binding

We already know that arrow functions don’t have their own this binding. Instead, they inherit it from their enclosing scope. So, call, apply, and bind cannot change the value of this when used with arrow functions.

const globalObject = this;
const foo = () => this;
const obj = { name: "obj" };

// Attempt to set this using call, apply, or bind is ignored
console.log(foo.call(obj) === globalObject); // true
const boundFoo = foo.bind(obj);
console.log(boundFoo() === globalObject); // true

This makes them predictable and especially useful in callbacks, where traditional functions can cause confusion.

Callbacks and this

The common issue with traditional function is that their this value is based on how they are called. Let’s see how it becomes confusing with traditional functions.

const user = {
  name: "Arif",

  greet() {
    console.log(this.name);
  }
};

// 1. Passing the method directly
setTimeout(user.greet, 1000); //undefined

// 2. Using bind to set the `this` value
setTimeout(user.greet.bind(user), 1000); // Arif

// 3. Wrapping the method call
setTimeout(() => {
  user.greet();
}, 1000); // Arif

We all know that the callback functions in setTimeout pushed into the event loop and later get executed. Here runtime environment push funnction reference and not the actual function call. So, when user.greet is called, it is called as a regular function and not method of user object.

In second case, we are using bind. In previous article, we have seen that bind creates a new function with the this value set to the provided value. So, in this case, user.greet.bind(user) will create a new function with this is already set to user object. So, even if setTimeout will push the function reference into the event loop it will still have this bound to user object.

In third case, we are wrapping the method call inside an arrow function (It will work even if we use traditional function). So, here when setTimeout will push the function reference into the evnt loop, it will be of this outer arrow function and not of user.greet. Later when this outer function is called with it’s reference, it will call user.greet() as method call and this is preserved here.

See how confusing is this this. That’s why devs working with JS take antidepressants. But arrow functions make it easier. Predictable and less confusing. As this for arrow function never changes, doesn’t matter how you call it.

Interactive demo

setTimeout stores a reference, not a call

Step through the three setTimeout variants from the article. Watch what the event loop holds and how this is decided when each timer fires.

Step 1 of 8: define user and greet

user and greet exist in scope, but nothing has been passed to setTimeout yet. Defining a method does not lock its this value.

const user = {
name: "Arif",
greet() {
console.log(this.name);
},
};
setTimeout(user.greet, 1000);
setTimeout(user.greet.bind(user), 1000);
setTimeout(() => user.greet(), 1000);

Swipe the panels →

Event loop: timer queue

  • greetnot scheduled

    bare function reference

  • boundGreetnot scheduled

    this locked to user

  • wrappernot scheduled

    outer arrow function

Now executing

Nothing scheduled yet.

Console output

Console: (empty)

In strict mode the first bare call gets this = undefined instead, so greet() throws a TypeError before it can log undefined.

const arrowCounter = {
  count: 0,
  start: function () {
    setTimeout(() => {
      // 'this' is inherited from the 'start' method's scope
      this.count++;
      console.log("Arrow:", this.count); // Logs "Arrow: 1"
    }, 1000);
  },
};
arrowCounter.start();

No arguments object

Arrow functions do not have their own arguments object. They can access the arguments object of the enclosing traditional function.

function foo(n) {
  const f = () => arguments[0] + n; // 'arguments' is from foo's scope
  return f();
}

foo(3); // 6 (arguments[0] is 3)

Make foo an arrow function and see what happens. Why do you get such output?

For accessing arguments within an arrow function, it’s better to use rest parameters.

const sum = (...args) => args.reduce((total, num) => total + num, 0);
sum(1, 2, 3); // 6

Cannot be used as constructors

Arrow functions cannot be used as constructors. Attempting to call them with new will result in a TypeError. They also don’t have a prototype property.

const Foo = () => {};
const foo = new Foo(); // TypeError: Foo is not a constructor
console.log("prototype" in Foo); // false

Cannot be used as methods

Arrow functions should not be used as methods on an object because they don’t bind this to the object.

const obj = {
  i: 10,
  b: () => console.log(this.i, this), // 'this' is the global object or undefined
  c() {
    console.log(this.i, this); // 'this' is 'obj'
  },
};

obj.b(); // undefined, Window/global object
obj.c(); // 10, { i: 10, b: [Function: b], c: [Function: c] }

Arrow functions as “auto-bound” methods in classes

When we use an arrow function as a property inside a class, it behaves like a methods that is automatically and permanently bound to the instance of that class. This is a very useful feature that helps avoid common problems with the this keyword.

Let’s break it down:

  1. Regular methods lose this: We just saw that in setTimeout, when we passed a regular method, it lost its this context. So, we need to bind it maually using bind. We will see a comparison example of how storing a reference to a regular method can lead to losing the this context.

  2. Arrow functions remember this: Arrow functiond oesn’t have its own this. It “remembers” the this from the context where it was created. Remember the cat meme from this article? No one can change the this of an arrow function. Now in case of class, for an arrow function defined as property, the this will always refer to the instance of the class, no matter how you call it.

This is why they are called “auto-bound” and now you don’t need to use bind.

Comparison with a regular method

class Player {
  constructor(name) {
    this.name = name;
  }
  // A regular method
  sayNameRegular() {
    console.log(this.name);
  }
  // An arrow function as a class field
  sayNameArrow = () => {
    console.log(this.name);
  };
}

const player = new Player('Alice');
// --- Calling them directly works for both ---
player.sayNameRegular(); // "Alice"
player.sayNameArrow();   // "Alice"

// --- Detaching the methods tells a different story ---
const regular = player.sayNameRegular;
const arrow = player.sayNameArrow;

// Calling the detached regular method fails
regular(); // TypeError: Cannot read properties of undefined (reading 'name')

// Calling the detached arrow function works perfectly
arrow(); // "Alice"

// Calling with `call` also works
regular.call(player); // "Alice"

Note: How arrow function captures this from the surrounding context differs in case of class and object.


Other limitations

  • No yield: The yield keyword can’t be used in an arrow function’s body, so they can’t be used as generator functions. However, yield can be used iwthin a generator function that is nested inside an arrow function.
const createGenerator = () => {
  // This arrow function contains and returns a generator function.
  return function*() {
	yield 1;
	yield 2;
  };
};
const newGenerator = createGenerator();
const generator = newGenerator();
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
  • Line breaks: Line break between the parameters and the arrow => throws syntax error.
  const func = (a, b, c)
  => 1;
// SyntaxError: Unexpected token '=>'
  • Operator precedence: The arrow has a lower operator precedence, which can lead to unexprected behavior with other operators like ||. Parathesis are required to ensure the correct order of operations.
    let callback;
    // This causes a SyntaxError
    callback = callback || () => {};
    // It considers `callback || ()` as the arguments list

    // This works
    callback = callback || (() => {});

I hope this article was helpful. It covered some jaw dropping spots of JavaScript. In next article, we’ll see currying in JS. It is a functional programming technique.


Related posts