Data Types and Variables

Before you bring dynamic styling and content to a Web page you need to know the coding lanaguage through which this can happen. Over the next few tutorials you are introduced to the JavaScript language. If you already know a programming language, you should see a lot of similarities in JavaScript. It has the same types of arithmetic and logical operations as other languages, along with the same types of branching and looping control structures. It should be a relatively simple matter of learning the syntactical differences in JavaScript.

Computer programs are processors of data. They take numbers, letters, and other special characters and manipulate them in some fashion for the purpose of producing information. They attempt, in other words, to assign meaning to bits and pieces of data by applying actions such as calculating, categorizing, arranging, presenting, or otherwise manipulating and organizing the data to derive useful information. In JavaScript, data are recognized as one of three types: numeric, string, and Boolean.

Numeric Data Type

Numeric data are composed of the numerals 0 - 9 plus the decimal point. JavaScript recognizes two kinds of numbers: integer numbers are whole numbers composed only of the decimal digits 0 - 9; floating-point numbers are composed of the decimal digits plus a decimal point. Thus, the value 12345 is an integer number and the value 123.45 is a floating-point number. JavaScript recognizes numbers when they appear in decimal notation (as above), in scientific notation (123.45E6), in hexadecimal (0XFF00CC), or in octal (012345). Numeric data are defined for the purpose of applying mathematical operations to them.

String Data Type

String data are composed of the lower-case alphabetic characters a - z, the upper-case characters A - Z, the numerals 0 - 9, plus special characters such as $, #, &, _, and others. Strings are identified by enclosing them in quotes: "This is a string of characters." Character strings are treated as single blocks of text that can be put together (concatenated) to create a longer character string from the separate strings, or they can be taken apart to extract substrings composed of portions of the string.

Since quotes are used to surround and define text strings, a special situation arises when you want to include quotation marks as part of a text string. You cannot just include them in the middle of the string as follows:

"Here is a string with "quote" marks inside."

This notation violates the definitional rules of a string and confuses JavaScript. Since pairs of quote marks surround and define a string, this line is interpreted as three separate elements: the string "Here is a string with " is followed by the word quote, which is followed by a second string " marks inside." This is clearly not what is intended.

There are a couple of ways to handle this situation. You can mark embedded quotes with a preceding backslash character (\), technically called escaping the quote character:

"Here is a string with \"quote\" marks."

This format indicates that the embedded quotation mark does not enclose a string; it is a character within a string. You can also enclose the entire string inside single quotes (apostrophes) to differentiate between the two quote types:

'Here is a string with "quote" marks.'

This latter technique of alternating quote characters is probably the easiest way to distinguish between embedded quotes and enclosing quotes, although it does beg the question of what to do about quoted strings that contain both embedded quotes and embedded apostrophes:

'Here's a string with "quote" marks.'

This construction is invalid because JavaScript interprets the apostrophe as ending the string begun with the initial single quote. So, you need to put together alternating quotes and escaped characters that make sense to JavaScript:

"Here's a string with \"quote\" marks." or
'Here\'s a string with "quote" marks.'

The point is, you need to be careful when composing text strings that themselves enclose quote marks and apostrophes to make sure that the entire string is treated as a single entity.

Boolean Data

Boolean data consists of two values: true and false. This data type is used in script decision making, a topic covered later where you will see the application of this data type.

JavaScript Variables

A computer program that processes data must set aside storage areas in computer memory where numeric, string, and Boolean data can be placed, and from which they can be accessed in order to process them. Programs create these storage areas by defining program variables.

A variable is a named memory location. Once defined, it is available as a place to store data temporarily while a program, or script, is running. The script can assign data to that location, retrieve data from the location for processing, and put processing results back into that location.

In JavaScript, a variable is created by naming it. There are, however, naming conventions that must be followed. Variable names

Otherwise, you are free to name your variables as you wish. It makes sense, of course, to assign names that are meaningful and that help identify the kinds of data being stored in the associated memory locations.

Variable names are case sensitive. That is, JavaScript differentiates between upper-case and lower-case characters. Therefore, variable My_Name references a different memory location from my_name or MY_NAME. Make sure you pay careful attention to the case of the variable names you assign and use them consistently.

Declaring Variables

The formal method of establishing and naming variables is to declare them in a JavaScript statement with the keyword var. This word is followed by the name you wish to assign to the variable as shown in the general format in Figure 2-1.

var variable
Figure 2-1. General format to declare a JavaScript variable.

This format is illustrated in the following examples of declaring variables inside a script.

var LastName;
var Soc_Sec_No;
var current_date;

Here, three different storage locations are named and set aside to contain data; plus, the variable names suggest the kinds of data to be placed in these locations. Any time a script needs to refer to or access the stored data, it does so through the names assigned to these locations. This is an important point. A script reference to a variable name is a reference to the actual data value residing in the named memory location.

Notice also in the above example that a semicolon is used to terminate each declaration statement. Doing so permits more than one statement to be placed on a single line of code by explicitly terminating each statement. If, however, only a single statement appears on a line, use of the semicolon is optional. The convention followed in these tutorials is to always terminate a statement with a semicolon, which is in keeping with common JavaScript practice.

Assigning Data to Variables

Data are placed into variables by using the JavaScript assignment statement. General formats for the assignment statement include those shown in Figure 2-2.

variable = number
variable = "string"
variable = true|false
Figure 2-2. General formats to assign data to variables.

The data value appearing on the right of the equal sign is assigned to (placed in) the variable named on the left of the equal sign. This value can be an integer or floating-point number, it can be a text string enclosed in quotes, or it can be one of the Boolean values true or false. For example, if you have declared the following variables,

var My_Number;
var My_String;
var My_Test;

then you can place data into these variables with the assignments:

My_Number = 12345;
My_String = "A text string";
My_Test = true;

As you can see, the keyword var is used only the first time a variable is declared. Subsequently, the variable name by itself references the existing variable.

You can see the results of these statements below. Click on the radio buttons in sequence to execute the statements and watch the declarations and assignments of values to the three variables.

Computer Memory:


Script:
var My_Number;
var My_String;
var My_Test;

My_Number = 12345;
My_String = "A text string";
My_Test = true;
Figure 2-3. Declaring and assigning values to variables.

Incidentally, you can combine the two actions of declaring a variable and assigning data to it within a single statement:

var My_Number = 12345;
var My_String = "A text string";
var My_Test = true;

This combined declaration and assignment is appropriate to establish the initial value for a variable when the value is known in advance. In many cases, however, you will not know the value that variable will take on; it will depend on the JavaScript processing that produces the value. In this case, you need only to declare the variable without assigning its value.

Technically, you do not have to use the var keyword. You can declare a variable and assign a value with, simply,

My_Number = 12345;
My_String = "A text string";
My_Test = true;

Still, it is conventional to follow the formal method of declaring a variable with the keyword var. You will also notice in the examples that blank spaces appear before and after the equal sign in the assignment statements. You can use spaces freely in JavaScript to make your code more readable.

Assigning Variables to Variables

In the above examples, literal data values are assigned to variables—an actual number, text string, or Boolean value is placed in the variable. You also can assign the contents of one variable to another variable with the syntax shown in Figure 2-4.

variable1 = variable2
Figure 2-4. General format to assign a variable value to a different variable.

Consider the following five lines of code:

var FirstString;
var SecondString;

FirstString = "Hello World";
SecondString = FirstString;
FirstString = "Goodbye World";

In the first two lines of code, two variables are declared, FirstString and SecondString. At this point, two memory areas have been set aside for storing data. The contents of these two variables are null, meaning that their data values are undefined.

In the third line, the text string "Hello World" is assigned to variable FirstString. In the next line, the value stored in FirstString is assigned to variable SecondString. That is, the data value "Hello World" that is sitting in variable FirstString is copied into variable SecondString. At this point, both variables contain the text string "Hello World". In the last line of code, the text string "Goodbye World" is assigned to variable FirstString. The data value "Hello World" is replaced by the value "Goodbye World".

Two important points: (1) When the contents of a variable is assigned to a different variable, it is copied from the source into the destination variable; it is not moved from the source to the destination variable leaving the source variable blank, or null. (2) When a data value is assigned to a variable, it replaces the current contents of the variable with the new value. These operations are illustrated below.

Computer Memory:
FirstString
SecondString


Script:
var FirstString;
var SecondString;

FirstString = "Hello World";
SecondString = FirstString;
FirstString = "Goodbye World;"
Figure 2-5. Assigning variables to variables.

Local Variables

Recall that JavaScript functions are the main processing entities in a script. It is inside functions that variables are declared and their values are established and manipulated.

Variables that appear inside functions are local variables. This means that the variables are "private" to those functions and are not accessible by other functions. The following script, for example, contains two functions, Process1() and Process2(), which declare the variables Data1 and Data2, respectively.

<script type="text/javascript">

function Process1()
{
  var Data1 = 123.45;
  process Data1...
}

function Process2()
{
  var Data2 = 678.90;
  process Data2...
}

</script>
Listing 2-1. Declaring local variables.

Variable Data1 is local to function Process1() and is unknown by and is inaccessible by Process2(). Likewise, variable Data2 is local to function Process2() and is unknown and inaccessible by Process1(). Both variables are "hidden" inside their respective functions. This means it would be perfectly valid to use the same variable name for two different variables in two different functions. The variables are isolated within their functions and would not be confused with each other. However, good programming practice is to use different names for different variables in all cases. In this way, the programmer, at least, does not become confused in keeping track of two different variables with the same name.

Passing Local Variables

In cases where complete and final processing of a variable can be accomplished within a single function, this isolation of local variables does not raise access issues. However, there may be occasion when a second function does need access to a local variable of the first function. In this case, it is necessary for the first function to call the second function and, at the same time, pass along its local variable for access by the second function.

The general format for one function to call upon the processing of a second function and to pass data values to the second function is shown in Figure 2-6.

function functionName1()
{
  functionName2(parameter1, parameter2, ...);
  ...
}
Figure 2-6. General format to call a function and pass data values.

A function makes a call to a different function through the latter's name. In this case, the function call includes a parameter list. That is, enclosed in the paretheses of the function call is a list of one or more local variables, separated by commas, which are made available to the called function. These variable names, of course, represent the associated data values that are stored in the variables and that are passed along to the function.

On the receiving end, the called function gains access to the passed data values. The general format for a function to capture data values passed to it is shown in Figure 2-7.

function functionName2(argument1, argument2, ...)
{
  process argument1...
  process argument2...
  ...
}
Figure 2-7. General format for a function to receive passed data values.

The called function includes an argument list. This is a list of one or more variables local to the receiving function where the data values passed to it are stored. The variable names assigned in the argument list do not have to match those in the parameter list. However, the data values that are received are captured in the order in which they are sent. That is, the first data value represented in the parameter list is stored in the first variable appearing in the argument list; the second data value in the parameter list is stored in the second variable appearing in the argument list; and so on. There is one-to-one matching between the data values sent through the parameter list and the variables in which they are stored in the argument list. Thereafter, the receiving function can process the passed data values just as if they were local variables, which they are.

Consider the following scenario. A function named Process1() declares local variable MyLocalData. Apart from its own processing of this value, Process1() needs to call upon function Process2() for addition processing of the variable. It calls Process2(), passing along the MyLocalData value to make it available to this second function.

function Process1()
{
  var MyLocalData = 123.45;
  ...
  Process2(MyLocalData);
}

function Process2(PassedData)
{
  process PassedData...
}

Listing 2-2. Passing a variable to a function.

Here, Process1() calls the second function and, at the same time, includes variable MyLocalData in the parameter list of the call: Process2(MyLocalData). Keep in mind that only the data value stored in the variable (123.45) is passed; the variable itself is not passed.

Function Process2() receives the passed data value through its argument list: Process2(PassedData). Variable PassedData is where the passed value is stored. Now, Process(2) can perform additional processing on the value, stored locally as PassedData.

Keep in mind that when a called function completes its processing, script control returns to the calling function, and processing continues with the statement following the function call. When the original function completes its processing, the script ends.

Returning Values from Functions

Often times, functions are called, not to continue a sequence of processing tasks, but to return a data value. A function, for instance, calls upon a second function to manipulate passed data values. The result of this processing is then returned to the calling function where processing continues with the returned value. A called function returns a data value with a return statement in the format shown in Figure 2-8.

function functionName(argument1, argument2, ...)
{
  ...
  return variable
}
Figure 2-8. General format to return a value from a function.

Suppose, for example, that a specialized function is created that multiplies any two numbers passed to it. It then returns the product to the calling function. Although you have not yet been introduced to JavaScript arithmetic operations, you should be able to follow the logic of the following function call and return.

function Process1()
{
  var Data1 = 10;
  var Data2 = 20;
  var Product = GetProduct(Data1, Data2);
}

function GetProduct(Number1, Number2)
{
  return Number1 * Number2;
}
Listing 2-3. Returning a value from a function.

Process1() declares two local variables, Data1 and Data2, and assigns them numeric values. It also declares local variable Product and assigns it the value returned from a function call to GetProduct(), passing along the values of Data1 and Data2 in its parameter list. GetProduct() receives the two values as Number1 and Number2 in its argument list. It returns the value of Number1 multipled by (*) Number2 to the calling statement where it is stored in variable Product.

Using functions that return processed values plays a big role in JavaScript programming. There are, in fact, many built-in functions that are part of the language and which perform and return the results of complex processing that is commonly needed in scripts, saving you the task of writing the required code. These built-in functions are introduced as needed throughout the tutorials. Also, you will have occasion to write your own functions to return values as situations dictate.

Global Variables

Sometimes two or more separate functions need access to the same variable and it is not practical to pass it back and forth among the several functions. In this case, the variable needs to be declared as a global variable.

A global variable is declared outside any functions. In the following example, variable GlobalVariable is declared inside the script block, but not inside either of the functions. Thereafter, GlobalVariable is directly accessible by both functions.

<script type="text/javascript">

var GlobalVariable

function Process1()
}
  process GlobalVariable...
}

function Process2()
}
  process GlobalVariable...
}
</script>
Listing 2-4. Declaring and accessing a global variable.

It is normally considered good programming practice to isolate variables inside functions, making them local variables, and explicitly passing them between functions that need access to them. There is no risk that these variables can be inadvertently corrupted by processing activities in other functions that are not given explicit access to them. At times, though, global variables can be used as a way to share their values among multiple functions where convenience overrides the risks.