JavaScript: Variables


In this JavaScript video tutorial, we demonstrate how to declare and use variables in JavaScript programs.

For this lesson, you will need an HTML file and a JavaScript file like the ones that we created in Lesson 1. We use a different JavaScript file, but our HTML file will be essentially the same, except for the filename and the name of the JavaScript file that it calls. The code files for this lesson are given below.

Variable Box


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>XoaX.net's Javascript</title>
    <script type="text/javascript" src="Lesson2.js"></script>


var X = 1;
X = 2;
document.write("<br />");
X = 3;
document.write("<br />");
document.write("<br />");

X = "drugs";
document.write("Just say \"no\" to " + X + "<br />");
X = "alcohol";
document.write("Just say \"no\" to " + X + "<br />");

The JavaScript file demonstrates some of the basic properties of variables. Although we have used the generic name "X" for the variable in this program, we will usually want to employ variables that are more specific to what the variable is used for, such as SchoolName or DateOfBirth. In the program for this lesson, the variable is not used for a specific purpose. So, I have given it a generic name X to indicate this.

At the beginning of the JavaScript file is the declaration and initialization of the variable. This line begins with the command "var" that tells the interpreter that the this is a variable declaration. Next, comes the name, which is followed by the integer value 1 that is stored in the variable. Of course, a semicolon is used at the end to signal the end of the line of code. All of this is followed by a function call to document.write() in the next line to print the value of the variable X.

In the next line, we change the variable's value to 2 and then print it in the line after that. Then we print a line break or a endline character, which drops the printing position to the beginning of the next line. This is accomplished via the HTML tag <br />. Then the variable is set to 3 and printed, followed by two line breaks.

Video Game

After the the two line breaks, the variable X is set equal to the string "drugs" and is printed inside the message 'Just say "no" to drugs.' Afterward, this is done with the string "alcohol" as well. Notice that this changes the type of the variable from an integer to a string. JavaScript variables can be of any type and that type can change at any time. The type of data stored in a variable can be as complex as an entire video game, like the one shown above.