1. Home
  2. Computing & Technology
  3. JavaScript

JavaScript Functions
5. The Scope of Variables

By , About.com Guide

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.

This tutorial first appeared on www.felgall.com and is reproduced here with the permission of the author.

Explore JavaScript
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript
  4. Javascript Tutorials
  5. Learn Modern JavaScript
  6. 3. Functions
  7. JavaScript Functions - The Scope of Variables>

©2010 About.com, a part of The New York Times Company.

All rights reserved.