The Lifetime of JavaScript Variables

If you declare a variable, using "var", within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, it's called a global variable and all the functions on your page can access it. The lifetime of these global variables start when they are declared, and ends when the page is closed.

In short, the lifetime of a JavaScript variable starts when it is declared.

Back Table of Contents Next