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.
I'd expect that the logical idiom to do that would be as follows:
if (window.myLibrary) myLibrary.someFunction();
However after some research on stackoverflow, the consensus seems to be that the correct idiom is this:
if (typeof myLibrary != "undefined") myLibrary.someFunction();
This idiom is given in several answers on stackoverflow, the most prominent example being this one:
How can i check whether a variable is defined in javascript
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?