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,
x
in the current scopex
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
).