Global Variables and Window Properties
You'll learn: How declaring variables with var (and function declarations) automatically creates properties on the browser's window object.
The Connection Between var and window
When you declare a variable with var at the top level of a script (outside any function), JavaScript doesn't just create a variable—it also creates a property on the global window object with the same name. The same thing happens with function declarations.
var myName = "Alice";
console.log(window.myName); // "Alice"
console.log(myName === window.myName); // true
function greet() {
return "Hello!";
}
console.log(window.greet); // [Function: greet]
console.log(window.greet()); // "Hello!"
Think of it like this: var and function declarations at the global scope write their names into the building's main directory (the window object), making them accessible through that directory.
Why This Matters
This behavior means global var variables aren't truly separate from window—they are window properties. If you modify one, you modify the other:
var count = 5;
window.count = 10;
console.log(count); // 10
This auto-registration doesn't happen with let or const, which create global variables that remain separate from the window object.
When You'll See This
Legacy code often relies on this behavior, and some older browser APIs expect certain global functions to be accessible as window properties. Understanding this connection helps you debug why a var variable appears on window during inspection.
Key Takeaway: Variables declared with var and function declarations at the global scope automatically become properties of the window object, creating a direct two-way link between the variable name and window.variableName.