Daniel Russell
Daniel Russell

Reputation: 23

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();

Upvotes: 2

Views: 1032

Answers (1)

prasun
prasun

Reputation: 7343

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();

Upvotes: 2

Related Questions