Question

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?

Was it helpful?

Solution 2

I tend to go for the first example, unless there is some really compelling reason why someone might set the library to "true" or something similar. Yes, if your code is running in someone else's environment (ie, you're building a public Javascript framework like JQuery) you may want to be as safe as possible with the type-checking, to ensure someone isn't misusing the library. But in my view, perfect type safety in Javascript is not quite so important as to make all your code extremely verbose, and occasionally difficult to read.

I also liked an answer from the linked question; you can use

if ('myLibrary' in window)

I think that one's just preference. To clarify, that one will evaluate true even if window.myLibrary is 'false', so you'd basically be checking whether it was defined at all.

OTHER TIPS

myLibrary could exist but be set to 0 or false in which case the first example will assume it doesn't exist at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top