Java Reference
In-Depth Information
Creating variables and giving them values
Before you can use a variable, you should declare its existence to the JavaScript engine using the
var
keyword. This warns the engine that it needs to reserve some memory in which to store your data
later. To declare a new variable called
myFirstVariable
, write the following:
var myFirstVariable;
Note that the semicolon at the end of the line is not part of the variable name, but instead is used to
indicate to JavaScript the end of a statement. This line is an example of a JavaScript statement.
Once declared, you can use a variable to store any type of data. As mentioned earlier, many other
programming languages (called strongly typed languages) require you to declare not only the
variable, but also the type of data that will be stored, such as numbers or text. However, JavaScript
is a weakly typed language; you don't need to limit yourself to what type of data a variable can hold.
You put data into your variables, a process called
assigning values
to your variables, by using the
equals sign (=). For example, if you want your variable named
myFirstVariable
to hold the number
101
, you would write this:
myFirstVariable
=
101;
The equals sign has a special name when used to assign values to a variable; it's called the
assignment operator
.
Declaring Variables
trY it out
Let's look at an example in which a variable is declared, store some data in it, and finally, access its
contents. You'll also see that variables can hold any type of data, and that the type of data being
held can be changed. For example, you can start by storing text and then change to storing numbers
without JavaScript having any problems. Type the following code into your text editor and save it as
ch2 _ example1.html
:
<!DOCTYPE html>
<html lang
=
"en">
<head>
<title>Chapter 2, Example 1</title>
</head>
<body>
<script>
var myFirstVariable;
myFirstVariable
=
"Hello";
alert(myFirstVariable);
myFirstVariable
=
54321;
alert(myFirstVariable);
</script>
</body>
</html>