Home > Mobile >  Is an exported variable in Javascript considered global?
Is an exported variable in Javascript considered global?

Time:08-06

This is something I've wondered for a while now. Say I have an express application. I have this export in its own file:

// my-var.js
export const myVar = new Thing();

Then I have the server creation where I access that variable:

// index.js
import { myVar } from './my-var';
import { myRoutes } from './my-routes';

function startServer() {
    myVar.doSomething(); /* 1 */

    const app = express();
    app.use('/', myRoutes);
    
    app.listen(port, () => {});
}

Finally, I have my routes, which also use that variable:

// my-routes.js

import { Router } from 'express';
import { myVar } from './my-var';

const router = new Router();

router.get((req, res) => {
    myVar.doSomething(); /* 2 */
    res.json({});
});

So my question is: Is .1 and .2 referencing the same variable? Or has it been instantiated twice? I would kind of think it's instantiated every time the file is imported, because importing a file runs the code in that file. So myVar = new Thing(); is executed every time that file runs.

CodePudding user response:

The script file is executed once and there is a single result of that file. If any object is exported, all the modules will refer to the same instance of that object.

const myVar = new Thing();

myVar is created only once and then exported.

You can try changing a property in one module and checking that property in another to be sure.

CodePudding user response:

"I would kind of think it's instantiated every time the file is imported, because importing a file runs the code in that file." Yeah, you are right. The exported variable is not global, this would create so much bugs. Each host file has its own unique binding with the imported file.

Every time you import a file, the code in it is executed "inside the hot file" and only once. After that, you can access inside the hot file whatever value exported with export. You just cannot re-assign it. Here is a quote from mdn:

The identifier being imported is a live binding, because the module exporting it may mutate it and the imported value would change. However, the module importing it cannot re-assign it.

  • Related