2

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();
4
  • i tried in Node.js REPL, it does prints 2 Commented Nov 24, 2015 at 18:04
  • Ah i see. in REPL it works. but running a file with this code called foo.js by typing "node foo.js" to the terminal prints undefined. wondering why it does that Commented Nov 24, 2015 at 18:09
  • 1
    stackoverflow.com/questions/19850234/… Commented Nov 24, 2015 at 18:09
  • that answers it. Thanks czheo! Commented Nov 24, 2015 at 18:14

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.