Variables is a location in the computer’s memory where a value can be stored for use by a program. All variables have a name, type and value, and should be declared with a var statement before they are used in a program, although using var to declare variable is no required. The action reserves the name as a variable to be used as a storage area for whatever data you might want to hold with it. Let us see how to declare and handle it.
Var I, j, k; Var strname = “jscript”;
Once a variable is declared, it is ready to be filled with its first value. This initializing is done with the assignment operator,=. You can initialize a variable at the same time its declared or at point thereafter in your script. Assigning a value when the variable is declared can help you remember what type value you originally meant the variable to hold.
Rules for variable names:
- Variable names are case sensitive
- They must begin with a letter or the underscore character
- It should not contain spaces
*Choosing meaningful variable names helps a script to be “selfdocumenting”
Lifetime of Variables
When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared.
If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.
A simple program to explain variables
This program declares all the variables to be used; a dialog prompt allows the user to enter the string representing the first of two integers that will be added, similarly for the second also. The prompt dialog returns the value typed by the user to the program as a string. Function parseInt converts its string argument to an integer. And finally the sum is stored in the variable sum and displayed in window.