1

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

1 Answers1

2

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();
prasun
  • 6,324
  • 9
  • 33
  • 56