Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
nodejs variable undefined when exporting

Hey I was wondering why the following returns undefined:

let variable;

module.exports.initialize = () => {
  variable = "123";
};

module.exports.variable = variable;


I simply require the module in file A and then call the initialize function. In file B I require it and console.log the variable but it returns undefined. What am I missing here?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

module.exports.variable is a property on the module.exports object. When you initialize your module, you assign the value of variable to that module.exports.variable property and that value is undefined at the time you assign it (because the initialize() function has not yet been called).

So, when your module is done initializing itself, module.exports.variable is undefined.

Then, sometime later someone else calls module.exports.initialize() and that changes the local variable within your module to "123". That does not affect the value of the module.exports.variable property at all. It remains undefined.

In the future, please don't give either a property or a variable the name variable as it makes it very difficult to document or discuss. A different name that doesn't conflict with the English definition of the word variable would simplify discussing this code.


What you can do instead is export an object instead of a plain value.

let myObj = { name: "John"};

module.exports.setName = (name) => {
  myObj.name = name;
};

module.exports.sharedObj = myObj;

Then, why you import it somewhere else

const aModule = require('./otherModule');
console.log(aModule.sharedObj);         // {name: "John"}

aModule.setName("Bob");
console.log(aModule.sharedObj);         // {name: "Bob"}

Because objects in Javascript are assigned by pointer, when you did module.exports.sharedObj = myObj; in the module initialization, it put a pointer to myObj into module.exports.sharedObj so when myObj changes, anyone viewing module.exports.sharedObj will see that change too. This only works this way for objects in Javascript, not for other types of values (strings, numbers, etc...).

about 4 years ago · Juan Pablo Isaza Relatório

0

In JavaScript there are two types of values: 1) primitive type and 2) reference type. primitive values are always copied by their value and reference types are always copied by their references (not by their values).

Examples of primitive values: undefined, null, boolean, string, number. Examples of reference types: every types other than primitive types. e.g., Object, array etc. See the snippet below.

Example of Primitive type

let a = 10;
let b = a;

console.log(a);
console.log(b);

b = 20;

console.log(a);
console.log(b);

Example of Reference type

let obj_a = {value: 1}
let obj_b = obj_a;

console.log(obj_a);
console.log(obj_b);

obj_b.value = 20;

console.log(obj_a);
console.log(obj_b);

So when you declare the variable as let variable its value is undefined and when you assign module.exports.variable = variable then you're just setting it's value to undefined.

See the example below.

const myExports = {};

let variable;

function initialize() {
  variable = 10;
}

myExports.variable = variable;

console.log(variable);
console.log(myExports.variable);

initialize();

console.log(variable);
console.log(myExports.variable);

But if you were to initialize the the variable with a reference type e.g., an object then module.exports.variable would reflect any change to the properties of your variable variable.

Example:

const myExports = {};

let object = {};

function initialize() {
  object.value = 10;
}

myExports.variable = object;

console.log(object);
console.log(myExports.variable);

initialize();

console.log(object);
console.log(myExports.variable);

Hope it make sense.

about 4 years ago · Juan Pablo Isaza Relatório

0

try initializing the variable in the module.exports.initailize function

module.exports.initialize = () => {
    let variable;
    variable = "123";
};



module.exports.variable = variable;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda