1

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)

5
  • 1
    WHy not check window.mySuperProperty? shorter and more readable imo. Commented Jun 23, 2009 at 7:25
  • Is that wrapped in a function or simply in <script> tags? Commented Jun 23, 2009 at 7:28
  • 2
    "Checking" window.mySuperProperty is different. If you mean executing something like "if (window.mySuperProperty) {}" then you would simply check for the value of the mySuperProperty variable (that is in this case a property of global object) and not for the existance of it. Commented Jun 23, 2009 at 7:34
  • I see no use to check for the very existance of a property in JavaScript imo as it is a dynamic programming language. What´s interesting is if a variable/property is not equal to undefined. As an experiment it´s interesting though. Commented Jun 23, 2009 at 7:48
  • This is a great example of why I move all var declarations to the top of scope in JavaScript. Commented Jun 23, 2009 at 23:01

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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).
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.