3.2 VariablesVariables 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:
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 NamesVariable 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.
3.2.2 Declaring and Initializing VariablesVariables 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
3.2.3 Dynamically or Loosely Typed LanguageRemember, 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.
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
3.2.4 Scope of VariablesScope 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 VariablesTo 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
|