Ad

JavaScript Variable Without Var Inside Function Not Available In Global Execution Context

I learned in one of the kyle simpson's javascript courses that if we declare a variable inside a Javascript function without any prefixing var keyword, then that variable is made available in global execution context, but when I try it in chrome developer tool or nodejs it throws ReferenceError:....

Has anything changed ?

Happens in both Firefox and Chrome on Windows and Linux.

function foo() {
  bar = "I am in global scope";
}
foo();
console.log(bar);


    

ReferenceError: bar is not defined

The other question is about undefined being appended to the output log,I do not have any mention of it in this question. Not sure why this is marked as duplicate. This question is about global execution context / scope

Thanks.

Ad

Answer

Has anything changed ?

Not in loose mode, no, nor will it. JavaScript's steering committee, TC39, is quite rightly extremely conscious of backward-compatibility.

In strict mode, that code fails because bar is undeclared as of where you assign to it.

You've said that you're seeing this in Chrome's console and also in Node.js's REPL. I see undefined in both cases, but it's because those environments are showing the result of the call to console.log (which is undefined) after showing bar. I see "I am in global scope" first, then undefined (the result of calling console.log):

enter image description here

enter image description here

That saide, don't use the console for this sort of thing. :-) Consoles are a very special environment, particularly around scope, because of their interactive nature. If you want to know how something really works, and if it's even tangentially scope-related, it's best to replicate it in an actual file or script, not the console.

Ad
source: stackoverflow.com
Ad