54

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,487
  • 2
  • 13
  • 21

1 Answers1

47

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
  • 572,313
  • 128
  • 898
  • 1,281
  • 4
    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
  • @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