window.baz vs var baz. A subtle oddity.

While trucking away at $work, Jim pointed out a subtle nasty edge case in how JavaScript and the browser interact. Let’s say you have the following code:

    <title>shared var</title>
    <script type="text/javascript">
      var foo = "awesome";
      bar = "bartastic";
      window.baz = "bazzoom";
    <script type="text/javascript">
      if(! var foo = "not awesome";
      if(! var bar = "not bartastic";
      if(!window.baz) var baz = "not bazzoom";
    <p>Foo is <script type="text/javascript">document.write(foo);</script></p>
    <p>Bar is <script type="text/javascript">document.write(bar);</script></p>
    <p>Baz is <script type="text/javascript">document.write(baz);</script></p>

I think most folks would expect the output to be:

Foo is awesome

Bar is bartastic

Baz is bazzoom

and it is on Firefox, Safari and Opera, but on IE you get:

Foo is awesome

Bar is bartastic

Baz is not bazzoom

Care to guess why?


1 reply on “window.baz vs var baz. A subtle oddity.”

Because they’re in different script tags. Put them in the same script tags and it works as expected. This is bizarre because there is only one window object. Seems like IE creates a copy of a snapshot in time of the windows object for each script element before it begins interpreting any javascript or something.

This works as expected in IE:

(This is a repost, seems like my last post was ignored because I posted the code directly into the comment)

Comments are closed.