JavaScript tutorial:
The life of variables

 

The variables you declare can be global or local.

If you declare a variable outside of any function definition, it is a global variable. It lives for as long as your application lives. Any part of your program can access the global variable and change its value.

Variables created inside functions with the keyword var are local. Local variables have short lives: they come into existence when the function is invoked, and disappear when the function exits. The local variable can only be used and its value modified inside of a function declaring it.

A global and a local variable with the same name can coexist. They are in every way two different variables and modifying one does not affect the other. Here is an example:
 
str = "This is a global string";
function MyFun()
{
   var str = "This is a local string";
   document.write(str);
}
MyFun();
document.write(str);

To run the code, paste it into JavaScript Editor, and click the Execute button. The function MyFun() declares the local str variable and changing its value in no way affects the global str variable.

Points to remember:

Global variables can be accessed by other variables and functions.
Local variables can be accessed only within the function declaring them.
Variables declared inside a function without the keyword var are global.
When declared inside a function with the keyword var, the variable is local to the function declaring it.
Declaring a variable outside of a function makes it global.

Next