Read more

What `var` actually does in Javascript

Dominik Schöler
April 03, 2013Software engineer at makandra GmbH

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).


Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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).

Posted by Dominik Schöler to makandra dev (2013-04-03 15:00)