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

1

10

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;
Dilution answered 5/1, 2020 at 7:40 Comment(3)
It will only be called once.Imaginal
@AluanHaddad thank you how did you know it? btw is there any article suggested about this topic. Like in C++, #include means copy and paste, when I include a header file in C++ I know exactly what's happening... But in javascript I don't know how import export (kinda equivalent) work. I can only find articles about what's the difference between export and module.export, export vs export default etc. but can't find one about how it worksDilution
Modules are a complicated subject. In JavaScript they have certain semantics, C++ includes are completely different and are not modules at all. incidentally, this is one of the many reasons why C++ is getting a proper module system... finally. Regarding JavaScript, most of the literature on modules is technical or overly simplistic. You can find out from the ecmascript specification. as to how I know about it, wasting years of my life thinking about it, researching it, and discussing it with people on GitHubImaginal
B
3

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
Bruell answered 23/5, 2021 at 17:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.