JavaScript Variables

Friday, April 6, 2012

Just as other programming languages, JavaScript provides us with the ability to store data using variables. The purpose of a variable is simply to store information so that it can be accessed at a later time in the program. If you do not know what a variable is, think about a variable as being a box. You store things in the box so that you can access them at any time. You can take things out of the box or put things into the box. When you are done storing things in the box, you can remove the items from the box. The variable works in this fashion. It provides you with a temporary means to store information for later use.

Some Basic Rules

There are few rules when using variables. First, variable names must begin with a letter, the $ character, or the underscore character. Next, since JavaScript is case-sensitive, variable names are case-sensitive. Finally, each variable you use needs to have a unique name, otherwise, you will overwrite the data as the variable is assigned different values in your program.

Declaring a Variable

Declaring a variable in JavaScript is easy and straightforward. You declare JavaScript variables with the var keyword:

var name;
var id=12345;
var type="book"

In the first example, we declared a variable called "name", but did not assign it a value. In the second example, we declared a variable called "id" and assigned it a value of "12345". Note that we did not place quotes around the value of 12345 when we assigned it to the variable "id".  The value is assigned as a number.  In the next example, we declared a variable called "type" and assigned it a string value of "book".  The value for the variable called "type" will be treated as text.

Local vs Global Variables

A variable declared within a JavaScript function is considered to have a local scope.  A local variable can only be accessed within the function it was declared in. You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared. Local variables are deleted as soon as the function is completed.

Variables declared outside of a function are considered to have a global scope. All of the functions on the same web page can access global variables. Global variables are deleted when a user close the webpage.  If you asign a value to a variable that was not declared using the keyword "var", the variable will be declared as a global variable.

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

Murachs JavaScript and DOM Scripting JavaScript and jQuery: The Missing Manual Professional JavaScript for Web Developers