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?