Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

will export function() be called multiple times in javascript?

I wonder if this

const getData = () => {
  const data = 1; // simplified complicated operations 
  return data;
};

export default getData();

is any performance difference than this:

const getData = () => {
  const data = 1;
  return data;
};

const toexport = getData(); // cache to a variable before exporting
export default toexport;

The question boils down to how export actually works. I read many articles and I can manage to make it work, but I haven't understood what it does under the hood (couldn't find an article about my question).

What if an export is imported from difference import, will the getData() be called once or being called for each import?

function getData() {
  console.log('getData');
  return 1;
}

// will `export default getData();` be like this
const importSomeWhere = getData();
const importSomeWhereElse = getData();



// or this?
const exportCached = getData();

const importSomeWhere2 = exportCached;
const importSomeWhereElse2 = exportCached;
like image 614
Larry N Avatar asked Jan 05 '20 07:01

Larry N


People also ask

Can a JavaScript file have multiple exports?

Description. Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above syntax.

How does export work in JavaScript?

The export statement is used when creating JavaScript modules to export objects, functions, variables from the module so they can be used by other programs with the help of the import statements. There are two types of exports. One is Named Exports and other is Default Exports.

How do I export multiple items in JavaScript?

To export multiple functions in JavaScript, use the export statement and export the functions as an object. Alternatively, you can use the export statement in front of the function definitions. This exports the function in question automatically and you do not need to use the export statement separately.

Can I export multiple functions React?

Use named exports to export multiple functions in React, e.g. export function A() {} and export function B() {} . The exported functions can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a single file.


1 Answers

It will be evaluated only once. Here's example from What Happens When a Module Is Imported Twice?

In increment.js, we declare a variable called counter

let counter = 0;
counter++;

export default counter;

In consumer.js we import 2 times, but the counter is evaluated once for the first import

import counter1 from './increment';
import counter2 from './increment';

counter1; // => 1
counter2; // => 1
like image 75
onmyway133 Avatar answered Sep 27 '22 15:09

onmyway133