What's the difference between a global variable and a 'window.variable' in JavaScript?

Viewed 37289

I'm reading the Backbone.js documents and am seeing a lot of code that assigns attributes to the window object:

window.something = "whatever";

What's the difference between calling this code, and just assigning the variable and creating a global variable, like this:

something = "whatever";

I assume there is some kind of scope difference, and/or object ownership difference (window being the owner vs. not), but I am interested in the detail between the two and why I would use window vs. not use it.

5 Answers

Adding one more point:

If you refer an undeclared variable directly (without using - window or typeof) then you will get a variable is not defined error.

Examples:

// var unDecVariable

if (unDecVariable != null) // Error: unDecVariable is not defined
{
    // do something
}

if (window.unDecVariable != null) // No Error
{
    // do something
}

if (typeof unDecVariable != 'undefined' && unDecVariable != null) // Alternative way
{
    // do something
}
Related