2

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?

moesef
  • 4,641
  • 16
  • 51
  • 68
  • I think the real problem is why logging `bar` doesn't throw error. At least I am curious about that. – alpakyol Mar 07 '14 at 07:54
  • Why did you need to post all that other code when your question is just about the difference between `baz` and `window.baz`? – Barmar Mar 07 '14 at 07:59
  • cause that was what I got asked verbatim. I guess I could have removed the other stuff. – moesef Mar 07 '14 at 08:00
  • The interviewer was trying to make it hard for you by throwing in irrelevant junk to confuse you. Your goal when asking on SO should be the exact opposite. – Barmar Mar 07 '14 at 08:09

3 Answers3

1

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.

Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
0

Because function definitions are evaluated before execution, variable assignment expressions are not.

shredmill
  • 283
  • 3
  • 10
0

This is because console.log(window.baz); is trying to find the variable inside window object where as console.log(baz) is trying to get a standalone variable, which is not defined yet.

Santosh Pradhan
  • 149
  • 1
  • 11