65

Which is better to do: export a const arrow function, like so:

export const foo = () => 'bar'

or export a regular function, like so:

export function baz() {
  return 'bar';
}

They compile like so:

exports.baz = baz;
function baz() {
  return 'bar';
}
var foo = exports.foo = function foo() {
  return 'bar';
};

It looks like using the const/arrow function combination declares an extra variable (foo), which seems to be an unnecessary extra step over the simple function declaration.

abustamam
  • 1,597
  • 2
  • 13
  • 21

1 Answers1

62

The differences are minuscule. Both declare a variable.

  • A const variable is constant also within your module, while a function declaration theoretically could be overwritten from inside the module
  • An arrow function is a function expression, not a function declaration, and the assignment can lead to problems for circular dependencies
  • An arrow function cannot be a constructor or use a dynamic this
  • An arrow function is a few characters shorter if you use a concise body and a few characters longer if you use a block body.
  • A function declaration better expresses intention to be callable. The arrow function stored in a const can get lost among other consts.
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 5
    So architecturally speaking, as long as the function does not need a constructor or `this`, a `const` variable should be fine? Can you elaborate on point number 2, re: circular dependencies? – abustamam Sep 20 '16 at 04:09
  • 1
    @MarosIvanco re your edit: a function declaration does not create a constant. Module exports are immutable from the outside only. – Bergi May 21 '20 at 15:08
  • Other considerations can be made, such as some mocking libraries can't support testing if arrow functions are called, but they can if regular functions are used. For example, typemoq: `For static mocks, TypeMoq is able to verify any inner calls inside regular functions but not inside lambda ones. E.g.:` – ps2goat Oct 27 '22 at 18:49
  • @ps2goat That appears to be a shortcoming of the `TypeMoq` library and of class fields, less of arrow functions. Similar to "not being able to reassign a function expression" when you use `const`. – Bergi Oct 27 '22 at 21:59