Benefit of using 'window' prefix in javascript

This is useful when attempting to test global object values. For example, if GlobalObject is not defined then this throws an error:

if(GlobalObject) { // <- error on this line if not defined
    var obj = new GlobalObject();
}

but this does not throw an error:

if(window.GlobalObject) { // Yay! No error!
    var obj = new GlobalObject();
}

Similarly with:

if(globalValue == 'something') // <- error on this line if not defined
if(window.globalValue == 'something') // Hurrah!

and:

if(globalObj instanceof SomeObject) // <- error on this line if not defined
if(window.globalObj instanceof SomeObject) // Yippee! window.prop FTW!

I would not expect to see a significant performance difference, and the only other reason you might do this is to ensure that you are actually getting a value from the global scope (in case the value has been redefined in the current scope).


I doubt there is any measurable performance benefit. After all the scope chain would be scanned for the identifier window first then the window object would be scanned for the desired item. Hence more likely it would be deterimental to performance.

Using window prefix is useful if you have another variable in scope that would hide the item you may want to retrieve from the window. The question is can you always know when this might be? The answer is no. So should you always prefix with window? What would you code look like if you did that. Ugly. Hence don't do it unless you know you need to.