Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 505
abustamam Avatar asked Sep 19 '16 21:09

abustamam


People also ask

Can you export an arrow function?

To export arrow functions in JavaScript, we can use export directly with arrow functions. const hello = () => console. log("hello"); export default hello; to export the hello function as a default export with export default .

Can we default export arrow function in JS?

You cannot name a default export.

Can you export a const?

Use named exports to export constants in JavaScript, e.g. export const A = 'a' and export const B = 'b' . The exported constants can be imported by using a named import as import {A, B} from './another-file. js' . You can have as many named exports as necessary in a file.

What's the difference between export and export default?

Exports without a default tag are Named exports. Exports with the default tag are Default exports. Using one over the other can have effects on your code readability, file structure, and component organization. Named and Default exports are not React-centric ideas.


1 Answers

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.
like image 78
Bergi Avatar answered Oct 20 '22 20:10

Bergi