JavaScript Functions

The Scope of Variables

Using functions is the first situation where it makes a noticeable difference whether you define a variable as local or global. Any variables defined as local (using var) inside of a function are local to that function. The variable will only exist while the function is being run. A completely new variable will be created each time that you call the function. If there is a variable outside of the function that has the same name as the one defined locally inside the function, the previously defined one will not be able to be referenced from anywhere within the function. The name is being used to refer to the locally defined variable.

Variables that are first defined within a function and which do not specify var will be defined as global variables. They will continue to exist and be able to be referenced after the function has finished.

It is bad programming practice to define global variables inside of a function. You can't easily tell if the variable already exists if it is created from within a function. With those globally defined variables that we have used in our sample code, we have defined the variable first outside of the function.. Variables defined using var outside of the function are still in scope when the function is called as long as the function doesn't define its own local variable with the same name.

go to previous section go to next section 

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate