3.2 Variables
Variables are fundamental to all programming languages. They are data items that represent a memory storage location in the computer. Variables are containers that hold data such as numbers and strings. Variables have a name, a type, and a value.
num = 5; // name is "num", value is 5, type is numeric friend = "Peter"; // name is "friend", value is "Peter", type is string
The values assigned to variables may change throughout the run of a program whereas constants, also called literals, remain fixed. (JavaScript 1.5 introduced constants and since they are so new, they are only recognized by Netscape 6.)
JavaScript variables can be assigned three types of data:
-
numeric
-
string
-
Boolean
Computer programming languages like C++ and Java require that you specify the type of data you are going to store in a variable when you declare it. For example, if you are going to assign an integer to a variable, you would have to say something like:
int n = 5;
And if you were assigning a floating-point number:
float x = 44.5;
Languages that require that you specify a data type are called "strongly typed" languages. JavaScript, conversely, is a dynamically or loosely typed language, meaning that you do not have to specify the data type of a variable. In fact, doing so will produce an error. With JavaScript, you would simply say:
n = 5; x = 44.5;
and JavaScript will figure out what type of data is being stored in n and x.
3.2.1 Valid Names
Variable names consist of any number of letters (an underscore counts as a letter) and digits. The first letter must be a letter or an underscore. Since JavaScript keywords do not contain underscores, using an underscore in a variable name can ensure that you are not inadvertently using a reserved keyword. Variable names are case sensitive; e.g., Name, name, and NAme are all different variable names. Refer to Table 3.2.
Table 3.2. Valid and invalid variable names.
Valid Variable Names |
Invalid Variable Names |
---|---|
name1 |
10names |
price_tag |
box.front |
_abc |
name#last |
Abc_22 |
A-23 |
A23 |
5 |
3.2.2 Declaring and Initializing Variables
Variables must be declared before they can be used. To make sure that variables are declared first, you can declare them in the head of the HTML document. There are two ways to declare a variable: either explicitly preceded by the keyword var, or not. Although laziness may get the best of you, it is a better practice to always use the var keyword.
You can assign a value to the variable (or initialize a variable) when you declare it, but it is not mandatory, unless you omit the var keyword. If a variable is declared but not initialized, it is "undefined."
FORMAT
var variable_name = value; // initialized var variable_name; // unitialized variable_name; // wrong
To declare a variable called firstname, you could say
var first_name="Ellie"
or
first_name ="Ellie";
or
var first_name;
You can declare multiple variables on the same line by separating each declaration with a comma. For example, you could say
var first_name, var middle_name, var last_name;
Example 3.5
<html> <head> <title>Using the var Keyword</title> <script language="JavaScript"> 1 var language="English"; // Variable is initialized 2 var name; // OK, undefined variable 3 age; // Not OK! var keyword missing ERROR! 4 document.write("Name is "+ name); </script> </head> <body></body> </html>
EXPLANATION
-
The variable called language is defined and initialized. The var keyword is not required here, but is recommended.
-
Because the variable called name is not initialized, the var keyword is required here.
-
The variable called age is not assigned an initial value. The var keyword is required. Without it, the program produces errors, shown in the output for Netscape and Explorer, in Figures 3.4 and 3.5, respectively.
Figure 3.4. Netscape error (JavaScript Console).
Figure 3.5. Internet Explorer error.
-
This line will not be printed until the variable called age is defined properly. Just use the var keyword as good practice, even if it isn't always required!
3.2.3 Dynamically or Loosely Typed Language
Remember, strongly typed languages like C++ and Java require that you specify the type of data you are going to store in a variable when you declare it, but JavaScript is loosely typed. It doesn't expect or allow you to specify the data type when declaring a variable. You can assign a string to a variable and later assign a numeric value. JavaScript doesn't care and at runtime, the JavaScript interpreter will convert the data to the correct type. Consider the following variable, initialized to the floating-point value of 5.5. In each successive statement, JavaScript will convert the type to the proper data type; see Table 3.3.
Table 3.3. How JavaScript converts datatypes.
Variable Assignment |
Conversion |
---|---|
var item = 5.5; |
Assigned a float |
item = 44; |
Converted to integer |
item = "Today was bummer"; |
Converted to string |
item = true; |
Converted to Boolean |
item = null; |
Converted to the null value |
Example 3.6
<html> 1 <head> <title>JavaScript Variables</title> 2 <script language="JavaScript"> 3 var first_name="Christian"; // first_name is assigned a value 4 var last_name="Dobbins"; // last_name is assigned a value 5 var age = 8; 6 var ssn; // Unassigned variable 7 var job_title=null; </script> 8 </head> 9 <body bgcolor="lightblue"> <font="+1"> 10 <script language="JavaScript"> 11 document.write("<b>Name:</b> " + first_name + " " + last_name + "<br>"); 12 document.write("<b>Age:</b> " + age + "<br>"); 13 document.write("<b>Ssn:</b> " + ssn + "<br>"); 14 document.write("<b>Job Title:</b> " + job_title + "<br>"); 15 ssn="xxx-xx-xxxx"; 16 document.write("<b>Now Ssn is:</b> " + ssn , "<br>"); </script> 17 <body><p><img src="Christian.gif"></body> </html>
Output:
11 Name: Christian Dobbins 12 Age: 8 13 Ssn: undefined 14 Job Title: null 16 Now Ssn is: xxx-xx-xxx
EXPLANATION
-
This JavaScript program is placed within the document head. Since the head of the document is processed before the body, this assures you that the variable definitions will be defined first.
-
This is where the first JavaScript program begins.
-
The string "Christian" is assigned to the variable called first_name.
-
The string "Dobbins" is assigned to the variable called last_name.
-
The number 8 is assigned to the variable called age.
-
The variable called ssn is not assigned any value at all. It is an uninitialized variable. The return value is undefined.
-
The value null is assigned to the variable called job_title. Null is used to set a variable to an initial value different from other valid types, but if used in an expression the value of null will be converted to the appropriate type.
-
The document head ends here.
-
The body of the document starts here.
-
A new JavaScript program starts here. All the variables declared in the head of the document are available here. Variables that are available throughout the entire document are called global variables.
-
The document.write() method concatenates the values of the strings with the + sign and sends them to the browser to display on the screen.
-
The value of the variable called age is displayed.
-
The variable called ssn was declared, but not initialized. It has no value, which JavaScript calls undefined.
-
The variable job_title was assigned null, a place-holder value. The null string is returned.
-
The variable ssn is assigned a string value. It is no longer undefined. Even though the variable was declared in the head of the document, as long as it was declared, it can be assigned a value anywhere else in the document.
-
The value of the variable ssn is displayed. Figure 3.6 shows the output in Internet Explorer.
Figure 3.6. Output from Example .
3.2.4 Scope of Variables
Scope describes where a variable is visible, or where it can be used, within the program. JavaScript variables are either of global or local scope. A global variable can be accessed from any JavaScript script on a page, as shown in Example 3.6. The variables we have created so far are global in scope.
It is often desirable to create variables that are private to a certain section of the program, thus avoiding naming conflicts and accidentally changing a value in some other part of the program. Private variables are called local variables. Local variables are created when a variable is declared within a function. Local variables must be declared with the keyword, var. They are accessible only from within the function from the time of declaration to the end of the enclosing block, and they take precedence over any global variable with the same name. (See Chapter 7, "Functions.")
3.2.5 Concatenation and Variables
To concatenate variables and strings together on the same line, the + sign is used. The + sign is an operator because it operates on the expression on either side of it (each called an operand). Sometimes the + sign is a string operator and sometimes it is a numeric operator when used for addition. Addition is performed when both of the operands are numbers. In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider these statements:
var temp = "The temperature is " + 87; // returns "The temperature is 87" var message = 25 + " days till Christmas"; // returns "25 days till Christmas"
But, if both operands are numbers, then addition is performed:
var sum = 10 + 5; // sum is 15
Example 3.7
<html> <head><title>Concatenation</title></head> <body> <script language="JavaScript"> 1 var x = 25; 2 var y = 5 + "10 years"; 3 document.write( x + " cats" , "<br>"); 4 document.write( "almost " + 25 , "<br>"); 5 document.write( x + 4, "<br>"); 6 document.write( y, "<br>"); 7 document.write(x + 5 + " dogs" , "<br>"); 8 document.write(" dogs" + x + 5 , "<br>"); </script> </body> </html>
Output:
3 25 cats 4 almost 25 5 29 6 510 years 7 30 dogs 8 dogs255
EXPLANATION
-
Variable x is assigned a number.
-
Variable y is assigned the string 510 years. If the + operator is used, it could mean the concatenation of two strings or addition of two numbers. JavaScript looks at both of the operands. If one is a string and one is a number, the number is converted to a string and the two strings are joined together as one string, in this example, the resulting string is 510 years. If one operand were 5 and the other 10, addition would be performed, resulting in 15.
-
A number is concatenated with a string. The number 25 is converted to a string and concatenated to " cats", resulting in 25 cats.
-
This time, a string is concatenated with a number, resulting in the string almost 25.
-
When the operands on either side of the + sign are numbers, addition is performed.
-
The value of y, a string, is displayed.
-
The + operators works from left to right. Since x and y are both numbers, addition is performed, 25 + 5. 30 is concatenated with the string " dogs".
-
Since the + works from left to right, this time the first operand is a string being concatenated to a number, the number is converted to string dogs25 and concatenated with string 5.