Variables

Variables store data that can later be retrieved or updated with new data. The data stored in a variable can be a value or expression. There are three types of expressions in the JavaScript language, which are described in Table.

JavaScript Expressions :

There are two types of variables: local and global. You declare local variables using the var keyword and global variables without using the var keyword. With the var keyword the variable is considered local because it cannot be accessed anywhere outside the scope of the place you declare it. For example, if you declare a local variable inside a function, it cannot be accessed outside of that function, which makes it local to that function. If you declare the same variable without the var keyword, it is accessible throughout the entire script, not only within that function.

Shows an example of a local variable, named num, which is assigned the value of 10.

Declaring a local variable

var num = 10;

To access the value of the num variable at another point in the script, you simply reference the variable by name, as shown below.

Accessing the value of a variable

document.write("The value of num is : "+num);

The result of this statement is "The value of num is 10." The document.write function writes data to the web page. You will use this function throughout the rest of this article to write examples to the web page.

To store arithmetic expressions in a variable, you simply assign the variable to the calculated value as shown below. The result of the calculation is what is stored in the variable, not the calculation itself. Therefore, once again, the result is "The value of num is: 10."

Storing an arithmetic expression

var num = (5+5);

document.write("The value of num is : "+num);

To change the value of a variable, refer to the variable by the name you assigned to it and assign it a new value using the equal sign (Below). The difference this time is that you do not have to use the var keyword because the variable has already been declared.

Changing the value of an existing variable

var num = 5;

document.write("The value of num is : "+num);

//Update the value of num to 15

document.write("The value of num is : "+num);

The result of this script is "The value of num is: 10" followed by "The new value of num is: 15."