Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

296
Vistas
Is an exported variable in Javascript considered global?

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.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

That's what we call a singleton pattern package design, when you do it like this:

export const myVar = new Thing()

You only create the Thing instance once, and afterwards everytime you import it, you're importing the same instance, because it's a reference now.

If you want to get a new reference everytime the myVar is imported, change the code

from:

export const myVar = new Thing()

To

export const myVar = () => new Thing()

And when you import it, use it as follows:

import { myVar } from './my-var'

const instance = myVar() // returns a new instance from Thing

// use the instance here, ex: instance.color
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda