Export const arrow function or basic function?

Ecmascript 6Babeljs

Ecmascript 6 Problem Overview


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.

Ecmascript 6 Solutions


Solution 1 - Ecmascript 6

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionabustamamView Question on Stackoverflow
Solution 1 - Ecmascript 6BergiView Answer on Stackoverflow