One of the most important aspects of JavaScript and jQuery, is a good understanding of global variables and local variables.

Variables are containers that hold a value. You use variables for many different things throughout your script. You may need them for values that change throughout the script or you may just need them for a short term.


Global Variables in JavaScript

Global variables are declared outside of any function. 

Global variables are recognized outside of all the functions and inside of all of the functions. Global variables are not deleted until the web page has been closed.

Use global variables for:

  • values that are used through out your script
  • values that may be changed in several different functions
  • values that you don't want to have to pass to a function


Local Variables in JavaScript

Local variables are declared inside a function.

Local variables are not recognized outside of that function. They are deleted when the function is completed.

Use local variables for:

  • values that are only used within the function

Note: if you use var to declare a variable inside of a function, its value will only be changed within that function, even if it has the same name as a global variable already declared.


Declaring global and local variables in JQuery

The following code illustrates declaring a global variable and a local variable.

    var grandTotal = 0; // this is a global variable
        var subTotal = 0;  // this is a local variable
        grandTotal = subTotal + 5;  // this is using a global variable inside the function