To arrow, or not to arrow. That is the question!

JS arrow functions are great, but when should we use them? And why might we choose not to use them?

Reading Time
2 min (~292 words)
Tags
Javascript
Typescript
Date
3/2/2023
To arrow, or not to arrow. That is the question!

JS arrow functions are great.

  • ✅ Concise
  • ✅ Optional implicit return
  • ✅ Don't have their own “this” context

But, I don't recommended using them everywhere.

We should prefer function declarations for top-level functions, here's why.

1// Looks like a variable at a glance (especially in larger files, this can seriously hurt readability) 👎
2// Order matters, since it's not hoisted 👎
3const add = (a: number, b: number) => a + b;
4
5// Looks like a function at a glance 👍
6// Order doesn't matter, since it's hoisted 👍
7function add(a: number, b: number) {
8  return a + b;
9}

You might say, "But the this context safety of arrow functions makes better!" To which I say no it doesn't - if you have need of a this context, it's not relevant to top-level functions, and isn't relevant for most functional style code either.

As with all things, use the right tool for the job. If you need to worry about this context, then handle that in the best way for your usecase.

Function declarations are weirdly looked down on nowadays compared to arrow functions, yet many people don't know there are some niche cases where arrow functions don't support the same things as function declarations.

The way I think about this: Do I need a callback or one-liner? Is this function nested? Use an arrow.

1[1, 2, 3].map((n) => n ** n);
2
3somePromise
4  .then(() => {
5    /* do something */
6  })
7  .catch(() => {
8    /* do something else */
9  });
10
11useEffect(() => {
12  // do something
13}, []);

Everything else as function.

1function add(a: number, b: number) {
2  return a + b;
3}
4
5function MyComponent() {
6  const [count, setCount] = useState(0);
7
8  const handleClick = () => {
9    setCount((c) => add(c, 1));
10  };
11
12  return (
13    <div>
14      <span>{count}</span>
15      <button onClick={handleClick}>Click me!</button>
16    </div>
17  );
18}