What `var` actually does in Javascript

Posted . Visible to the public.

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
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2013-04-03 13:00)