Search code examples
javascriptwindowglobal-variableshoisting

Javascript Global Reference Error


I got this question in an interview and I am curious as to why the two output different things:

(function() {
    console.log(bar);
    console.log(baz);
    foo();

    function foo() {
        console.log('aloha');
    }

    var bar = 2;
    baz = 3;
})();

ouputs:

undefined
Uncaught ReferenceError: baz is not defined 

whereas:

(function() {
    console.log(bar);
    console.log(window.baz);
    foo();

    function foo() {
        console.log('aloha');
    }

    var bar = 2;
    baz = 3;
})();

outputs:

undefined
undefined
'aloha'

what is the difference in the way that baz and window.baz are referenced? I though globals were automatically attached to window?


Solution

  • A ReferenceError indicates that an invalid reference value has been detected (ECMA 5 15.11.6.3)

    In practical terms, this means a ReferenceError will be thrown when JavaScript attempts to get the value of an unresolvable reference. (There are other cases where a ReferenceError will be thrown, most notably when running in ECMA 5 Strict mode. If you’re interested check the reading list at the end of this article)

    For further reading take a look here.