DEV Community

Eka Prasetia
Eka Prasetia

Posted on

function () {} Is Too Long

Originally written in 2020. Republished here with minor wording updates.

Arrow functions (aka fat arrows) landed in ES6 to help us write less JavaScript… and complain less about JavaScript.

Same logic, fewer characters. Everyone wins.

The idea

// Before
const add = function (a, b) {
  return a + b;
};

// After
const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

If your function is small, arrow functions keep it readable and out of the way.

Why people love them

Shorter code

Great for callbacks and utilities:

items.filter((x) => x.active);
Enter fullscreen mode Exit fullscreen mode

No ceremony. Just intent.

Implicit return

One expression? No return, no braces.

const square = (x) => x * x;
Enter fullscreen mode Exit fullscreen mode

Returning an object? Wrap it:

const user = (name) => ({ name, active: true });
Enter fullscreen mode Exit fullscreen mode

Yes, those parentheses are mandatory. JavaScript enjoys chaos.

Lexical this (aka fewer bugs)

Arrow functions don’t have their own this. They inherit it from the surrounding scope, which avoids a whole class of “why is this undefined?” moments.

const makeObj = () => ({
  value: 42,
  getValue() {
    return this.value;
  },
});

makeObj().getValue(); // 42
Enter fullscreen mode Exit fullscreen mode

Your future self says thanks.

When not to use them

Skip arrow functions if you need:

  • a constructor
  • arguments
  • a dynamic this

Arrows are tools, not religion.

Final thought

Arrow functions won’t fix bad logic—but they will make good logic easier to read.
And that’s already a big win in JavaScript land 🏹

Top comments (0)