abustamam
abustamam

Reputation: 1637

Export const arrow function or basic function?

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.

Upvotes: 69

Views: 47284

Answers (1)

Bergi
Bergi

Reputation: 664630

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.

Upvotes: 67

Related Questions