Search code examples
javascriptnode.jsscopeconsolestrict

Global Variable Scope Not recognized in Node.js console


So in a browser (chrome), if I run this code in the js console, the function call foo(); prints to the console the number 2. But if I run it in node.js, the function call foo() prints undefined. Why is this the case? Does node automatically run code in 'strict mode'?

function foo() {     
   console.log(this.a); 
} 

var a = 2; 

foo();

Solution

  • As mentioned in the document

    var something inside an Node.js module will be local to that module.

    So, it is going to be different.

    You can alternatively, try:

    function foo() {     
       console.log(this.a); 
    } 
    global.a = 2; 
    
    foo();