Skip to main content

Local and Global Variables

Some computer languages require you to declare a variable before you use it. JavaScript includes the varkeyword, which can be used to declare a variable. You can omit varin many cases; the variable is still declared the first time you assign a value to it.

To understand where to declare a variable, you will need to understand the concept of scope. A variable's scope is the area of the script in which that variable can be used. There are two types of variables:

  • Local variables have a single function as their scope. They can be used only within the function they are created in.
  • Global variables have the entire script (and other scripts in the same HTML document) as their scope. They can be used anywhere, even within functions.

To create a global variable, you declare it in the main script, outside any functions. You can use the var keyword to declare the variable, as in this example:

 
var students = 25;
 

This statement declares a variable called students and assigns it a value of 25. If this statement is used outside functions, it creates a global variable. The var keyword is optional in this case, so this statement is equivalent to the previous one:

 
students = 25;

<script language="JavaScript" type="text/javascript">
<!-
var interest_rate
interest_rate = 0.07
alert(interest_rate)
//->
</script>

 

Next: Declaring, Initialising and Using a Variable