tags:

views:

221

answers:

2

Consider this code:

<script type="text/javascript">
  if ('mySuperProperty' in window) 
  {
    alert(window['mySuperProperty']);
  }
  var mySuperProperty = 1;
</script>

Condition in if statement evaluates to true even though mySuperProperty isn't set yet. Why?

Update: Changed title, added <script> tag.

I stole this question from http://dfilatov.blogspot.com/2009/04/javascript.html (Russian)

+9  A: 

I guess this happens becuase: the JS code gets first parsed and analyzed. Variables and functions get instantiated at this time, but only during execution they will be assigned with their values used in declaratins. This is exactly why you get "undefined" in alert.

Sergey Ilinsky
Right, this explains why "if (window.mySuperProperty)" returns false (because "mySuperProperty" has no value) but "if ('mySuperProperty' in window)" returns true (because "mySuperProperty" does exist).
Steve Harrison
+1  A: 

The expression "window.mySuperProperty" checks the value of the mySuperProperty, which is at the time of the alert undefined

On the other hand mySuperProperty in window checks if the window has the mySuperProperty, which is checked in the whole window namespace (after every property name has been set).

Therefor,

if ('mySuperProperty' in window) returns true > the variable exists, but has no value yet if (window.mySuperProperty) returns false > undefined is a Falsy value.

ivb