Possible Duplicate:
Confused by Javascript's variable scope
For example, this is my JavaScript code:
var foo = 'Originalvalue';
var foo = 'Nextvalue';
alert(foo); // Nextvalue
So then, now I am sure writing var in front of an already-declared variable just simply is nullified and of no use to the program.
But then consider this program:
var foo = 'Originalvalue';
function duhfoo() {
var foo = 'Newbievalue';
}
duhfoo();
alert(foo); // Originalvalue
Then, from the logic explained in my first example, the value should be ‘Originalvalue’, as there is already a variable called foo. Then why is it like so?
In Javascript there are two kinds of variables: local variables and global variables.
When using
varoutside of functions you are declaring a global variable and the same happens if you don’t usevarat all. Writingat top level (outside any function) is the same as
var foo = "first".When inside a function however things are different, and the keyword
vardiscriminates between local and global variables:In other words when you use
varinside a function the variable will be a different one with the same name, visible only by code written inside the boundaries of the function.Please note that the boundary is determined by the function, and not the braces
{...}. If you have nested blocks and use anothervardeclaration inside the blocks the variable will be the same and this is different from what happens in other languages like Java, C or C++.The only way to create a scope is to define a function (including a function inside a function).
Another very important thing to remember in Javascript (especially if having been exposed to similar-looking languages in which this concept is not present like Java, C or C++) is the idea of “capture”/”closure”…
Basically a local variable can “outlive” the function that defined it, by being used by other functions that are said to “capture” that variable. A function that captures one or more variable is called “closure”.
In other words a local variable is only visible inside the body of the function, but it may live longer than then function like it happens for the local
fooof last example in which the variable survived after returning fromfbecause it has been captured by closureg.