Is it necessary to use the "typeof" operator to check if a variable exists in javascript?
<p>When I'm writing code that relies on objects created by another script file referenced from the same page I often find myself having to test for the existence of some global variable or another.</p>

<p>I'd expect that the logical idiom to do that would be as follows:</p>

<pre><code>if (window.myLibrary) myLibrary.someFunction();
</code></pre>

<p>However after some research on stackoverflow, the consensus seems to be that the correct idiom is this:</p>

<pre><code>if (typeof myLibrary != "undefined") myLibrary.someFunction();
</code></pre>

<p>This idiom is given in several answers on stackoverflow, the most prominent example being this one:</p>

<p><a href="http://stackoverflow.com/a/519157/1469919">How can i check whether a variable is defined in javascript</a></p>

<p>However, I can't find any explanation for why the second version is preferable. All the recommendations for it are in the form "just use this." Can someone please explain why using the typeof operator is superior to checking for the object by referencing it as a property of the window object?</p>
