I declared a global variable a
in lib.js
and exported 2 functions init_a
and return_a
from the lib.js.
Calling init_a
will initialise the undefined a
into value (I used date time for the example).
Calling return_a
will first check if a
is defined and return it immediately. Otherwise, it will call init_a
before returning it.
I am having a little confusion now because I couldn’t understand why a
is giving me different value depending on whethere init_a
is called explicitly or not. Following are the source codes:
// lib.js
let a;
function init_a() {
const init_time = new Date().getTime();
console.log(`init_a ${init_time}`);
a = init_time;
}
function return_a() {
console.log(`return_a`);
if (!a) {
console.log(`No a found, creating a new a`);
init_a();
}
console.log(`return_a return`);
return a;
}
module.exports = {
init_a,
return_a,
};
// main.js
const { init_a, return_a } = require("./lib");
function main() {
console.log("[DEBUG] main");
// init_a();
a = return_a();
console.log(a);
}
module.exports = main;
// main2.js
const { init_a, return_a } = require("./lib");
function main() {
console.log("[DEBUG] main2");
init_a();
a = return_a();
console.log(a);
}
module.exports = main;
// index.js
const main = require("./main");
const main2 = require("./main2");
async function __main__() {
main();
await sleep(1000);
main2();
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
(async () => {
await __main__();
})();
Output of node index.js
[DEBUG] main
return_a
No a found, creating a new a
init_a 1721288726594
return_a return
1721288726594
[DEBUG] main2
init_a 1721288727596
return_a
return_a return
1721288727596
Here we noticed the value of a
is different from the context of main
and main2
Output of node index.js
after commenting init_a
in main2.js
[DEBUG] main
return_a
No a found, creating a new a
init_a 1721288786523
return_a return
1721288786523
[DEBUG] main2
return_a
return_a return
1721288786523
Here we noticed the value of a
is the same in both the context of main
and main2
—
I couldn’t wrap my head around the behavior. Can someone please enlighten me :).
I have created a repo that contains all of the files, you can simply clone and run with node index.js
in your terminal!
https://github.com/tanshinjie/stackoverflow-qn-on-js-scope.git
Thank you!
I have read about lexical scoping in JS but I am not exactly sure if that is what happening in this case.
shinjie is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1