Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

global variable in Node.js: weird behaviour

I have below couple of files of javascript:

const { testFunc2 } = require("./TestFunction");


function home(val){
    global.context={};

    global.context.val = val;
}

home(3);
testFunc2();
//homeFunction.js

Below is TestFunction.js:

exports.testFunc2=()=>{
    console.log(context.val);
}

This code prints 3 as the output, even though I have not put global before context in testFunc2. How does this actually works? My guess is that node looks for a variable named context in local scope, if it is not able to find it local, it moves onto global scope. Is that correct?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

Yes, the explicit global object is a feature peculiar to Node JS

It is an object that is shared between all the modules in a Node JS program, even when you don’t feel like you are actively doing anything to cause the sharing (as you say).

If there is no local variable called context, your reference to context falls through to the global context, which you wrote into using global.context=.

In a way, it is similar to what would happen in a browser if you wrote to window.xyz and then imported a module that tried to read xyz.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading