What `var` actually does in Javascript

TL;DR: Variables not declared using var are stored outside the current scope, most likely in the global scope (which is window in web-browsers).


Declaring a variable in Javascript is done like var x = 5. This creates a new variable in the current scope (e.g. the function you're in). What happens when don't use var?

Javascript needs to be clever when you do an assignment without declaring a variable, e.g. x = 7. To find that variable,

  • it first looks up x in the current scope
  • next, it goes up the scope chain, looking for x
  • finally it hits the global scope

When it finds an existing property or variable named x, it assigns the new value. If it doesn't, a new global property is created and assigned the value (7).

Dominik Schöler About 11 years ago