Pavel Chuchuva
Pavel Chuchuva

Reputation: 22465

Variables as properties in JavaScript

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?

Try it yourself.

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

Upvotes: 1

Views: 296

Answers (2)

ivb
ivb

Reputation: 167

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.

Upvotes: 1

Sergey Ilinsky
Sergey Ilinsky

Reputation: 31535

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.

Upvotes: 9

Related Questions