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?

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.

Leave a Reply