1

Why is it that within Google Chrome, if I open the console and put in the following logic...

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

var bar = "global";
foo();

...I get "global" as a result for calling foo();

But if I place the same logic into a file called app.js within Visual Studio Code, and from the terminal run node app.js, I get undefined ?

5
  • 1
    Node.js does not create implicit globals. Commented Jan 10, 2018 at 22:02
  • Additionally to what @SLaks said: browsers consoles are unique environments with a lot of tiny nuances: if you want to ensure something works as expected - put your js in a <script> tag and run. Commented Jan 10, 2018 at 22:05
  • ahhh - That may be a good thing if I am trying to avoid implicit globals overall in my understanding of JavaScript. Thank you node.js for preventive measures! Commented Jan 10, 2018 at 22:14
  • 2
    You should always use 'use strict'; Commented Jan 10, 2018 at 22:20
  • In a browser, the global window object is the default context for this. Commented Jan 10, 2018 at 23:10

1 Answer 1

1

In browser

function foo() {
    console.log( this.bar ); //"this" point to "window" it equals to: console.log(window.bar)
}

var bar = "global";
foo();

In Node.js

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

bar = "global"; //implicit declaration variable will be global object's property
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.