CIS 209 Web Page Scripting Languages

Chapter 4: Data Storage

We will use JavaScript and VBScript to implement variables, constants and arrays.

Variables

Variables are used to store data that can be retrieved at a later time. Variables consist of two parts: variable name and data type. JavaScript and VBScript follow generic programming naming conventions but each has different rules for naming and declaring variables. The data type identifies what kind of data the variable can store.

Variable Declaration

Declaring a variable is the process of reserving the memory space for the variable before it is used. Although neither JavaScript nor VBScript requires you to declare variables, declaring variables is a good programming practice. Variables are declared within the scope in which they are being used. Some variables are used within a local function and other are application or global variables.

While JavaScript uses the keyword var to declare a variable, VBScript uses the keyword dim . Variables declared with var or dim exist as long as the procedure in which they are declared exists. Naming conventions make it easier to identify the type of variable. For example, it is common to name a variable that stores a string with the prefix str before the variable name - such as strProduct . We can declare multiple variables at the same time by adding a comma before the next variable name. The syntax to declare a variable is:

var VariableName; in JavaScript or
dim VariableName in VBScript

We can declare several variables on a single line with:

var strProduct, intQuantity, intPrice; in JavaScript or
dim strProduct, intQuantity, intPrice in VBScript

VBScript allows programmers to set an option that requires all variables to be declared before they are used. Setting this option helps to avoid misspelling errors in variable names. We use the keywords Option Explicit to force variables to be declared before they are used. On the Web server, we use <% option explicit %> .

Data Storage and Retrieval

We use the equal sign (=) in JavaScript and VBScript to store values in variables with the following syntax:

VariableName = Value

If a variable has not been assigned a value before it is retrieved, the value "undefined" is assigned to it. This EXAMPLE demonstrates how to declare and assign variables using both JavaScript and VBScript.

Calculating Values Based on User Input from a Form

Modifying the quantity of the item in the oatmeal cookie example above would require reprogramming the Web page since all our values were hard coded. We can use what we've learned in the last chapter about accessing objects, properties and events using the Document Object Model to assign values to variables entered into a form.

The value of variables can be used to store information obtained from users. When the user submits the form, the script calculates the cost based on the quantity ordered. The following example demonstrates how to retrieve values from a form using both JavaScript and VBScript. To retrieve the value of a text box from the form field, you must use the value property. The Web page will assign a value to a variable based upon the value entered on a form. Here is the EXAMPLE.

In VBScript, we do not use curly braces in functions. We end a function in VBScript with the key words end function .

Naming Variables

VBScript is not case sensitive, but JavaScript is case sensitive. This means that a variable named intPrice will be the same as INTPRICE and intprice in VBScript. However, JavaScript will treat these three variables as three totally different variables.

Use a descriptive name to name your variables so that it is easy to follow the logic of your program.

JavaScript Variable Naming Rules:

  1. variable names must begin with a letter, an underscore ( _ ), or a dollar sign
  2. the rest of the letters can be letters, numbers or underscores
  3. variable names cannot contain spaces
  4. variable names can NOT be a reserved word

Reserved words are words that have a predefined meaning that cannot be changed by programmers. The reserved words in this list cannot be used as JavaScript variables, functions, methods, or object names. Some of these words are keywords used in JavaScript; others are reserved for future use.

abstract
boolean
Boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
val
void
volatile
while
with

VBScript Variable Naming Rules:

  1. variable names must begin with a letter
  2. variable names may not contain a period
  3. variable names cannot be longer than 255 characters
  4. variable names must be unique within their scope
  5. variable names cannot contain spaces

Data Types and Naming Conventions

A variable's data type determines they type of data that it can store. It is a standard convention to begin variable names with a three-character prefix to identify its data type. The following table provides commonly used variable prefixes for various data types:

Variable Subtype Prefix Example
Booleanbln blnYes
Bytebyt bytZero
Date or Timedtm dtmToday
Doubledbl dblPrecision   
Errorerr errMessage
Integerint intPrice
Longlng lngNumber
Objectobj objShipping
Singlesng sngAverage
Stringstr strProduct
Real Number (used in JavaScript)    flt fltWeight

VBScript Data Types

VBScript has only one data type, called a variant. A variant data type contains a collection of data types called subtypes. The variant data type means that you must identify the data type by examining the contents of the variable. To distinguish between numbers and text, you can use quotes to distinguish the text subtype. The advantage of using a variant data type is that you can place any type of data in the variable, and the variable will behave according to the type of data it stores.

The date subtype is used for variables that store dates. A Boolean value only has two possible values; true/false, yes/no, on/off, 0/1, or any set of exactly two values. Variables that store monetary values use the subtype called currency. Variables can also contain objects, which allows programmers to access all the object's properties and methods using the variable. The following table lists commonly used variant subtypes and a description of the values they contain.

Subtype Description
Empty Uninitialized
NullContains no valid data (" ")
BooleanA logical value of either True or False
ByteContains integers from 0 to 255
IntegerContains integers from -32,768 to 32,768
Currency-922,337,203,685,477.5808 to 922,337,203,685,477.5807
LongContains integers from range -2,147,483,648 to 2,147,483,647
SingleContains a single-precision, floating-point number in the range -3.402823E38 to
-1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values
DoubleContains a double-precision, floating-point number in the range -1.79769313486232E308
to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values
Date (Time)Contains a number that represents a date between January 1, 100 to December 31, 9999
StringContains a variable-length string that can be up to approximately 2 billion characters in length
ObjectContains an object
ErrorContains an error number

JavaScript Data Types

Unlike VBScript, JavaScript has several data types; string, integer number, floating-point number, Boolean, object, null and undefined. Dates are handled as objects, not numbers. The typeof method, which takes one argument, the name of the variable, will return the data type of the variable as in typeof(VariableName). The following EXAMPLE illustrates how the typeof method can be used to return the data type of a variable.

The string is a value that is enclosed in double quotation marks. If the value in the variable contains a quotation mark, the value must use a single quotation mark. We can swap those around, placing double quotes inside single quotes. A string can contain an empty value - considered a zero-length or empty string, not the same as a null or undefined value.

Escape Characters in JavaScript

Strings in JavaScript can contain values other than alphanumeric characters. These non-alphanumeric characters have an assigned escape character that identifies the special character. To add these non-alphanumeric values to a string, we use the escape sequence. The escape sequence is a backslash ( \ ) followed by the escape character listed below:

Special Character Escape Sequence
Carriage Return      \r
Backslash     \\
New Line     \n
Tab Space     \t
Backspace     \b
Single Quotation Mark     \'
Double Quotation Mark          \"
Form Feed     \f

Although VBScript offers the MsgBox and InputBox to display messages similar to the JavaScript window.alert method, these are only available with the Internet Explorer browser.

The JavaScript numeric data type supports integers and real numbers. Integers are whole numbers; negative, positive, or zero. A real number is referred to in JavaScript as a floating-point number. Quotation marks determine whether a number is treated as a string or a number.

The Boolean data type stores the values as true or false. Boolean values must be entered without quotes or it will be treated as a string. Values are case sensitive and must be either true or false.

The object data type will be returned for variables that contains objects. A variable assigned to a date object will return the object data type. A variable assigned to null will return an object data type because null is an object. The variable that is defined as null has no value assigned. A null variable is not the same thing as an empty string. The null variable returns the data type "object" not "string".

Scope

Variables are defined with a scope. The scope is the location in which the variable can be used. Local variables are variables that can only be used by a portion of a program. Global variables can be used throughout the entire program. Variables declared within a function are local variables. Variables declared outside of a procedure or function are global variables.

In client-side programming, global variables are defined in the <HEAD> section and can be used anywhere within that Web page. In server-side programming, we can define global variables that can be used across Web pages and across users. JavaScript and VBScript handle the scope of variables differently in client-side scripts.

Variable Scope in JavaScript

In this EXAMPLE program, two global variables are defined in the first script, which is located in the heading. Only the global variables can be called from the second script within the body tag. We can prefix global variables with g or gbl to make the code easier to modify.

Variable Scope in VBScript

Similar to JavaScript, a variable's scope in VBScript is determined by where the variable is declared. In VBScript, variables declared in a local procedure, event handler or sub-procedure are called procedure-level variables, and can only be seen by the function that declared the variable. Variables declared in the heading section within event handlers and sub-procedures are still local variables. Global variables must be declared inside a script located in the heading section, but not within a function, procedure or event handler.

This VBScript Scope EXAMPLE is similar to the JavaScript Scope example. There are differences. In addition to the lack of a semicolon and curly braces, VBScript uses the dim keyword instead of var. Also, VBScript uses the end function statement to identify the end of the function instead of curly braces. Finally, the statement that retrieves the current date does not use the keyword new in VBScript.

Special Characters in VBScript

Instead of escape characters used in JavaScript, VBScript uses the chr function to return special characters. The chr function takes one argument, the number of the ANSI character code with the syntax: chr(ANSIcode). Several of the more commonly needed characters are: linefeed character - chr(10), carriage return - chr(11), backspace - chr(8), and tab space - chr(9). Also, we can use Constants such as vbLf for chr(10), vbCr for chr(13), etc. just as we can in Visual Basic. Let's loop through all of the 254 special characters in VBScript with the following EXAMPLE.

Constants in VBScript

A constant is similar to a variable except that its value is a specific, unchanging value. For example, pi is a common constant that represents the number 3.14159265358979323846 etc. To avoid having to remember the number, we can use a constant to refer to it. Constants are declared using the const keyword. They're often stored in an external file, sometimes referred to as a library or server-side include, and can be reused across Web pages. Intrinsic constants are constants that are built into the VBScript scripting language. The syntax for declaring a constant for a string, number and date are as follows:

Const conConstantName = "Value"
Const conConstantName = Number
Const conConstantName = #MM-DD-YY#

Constants are used for values that are referred by various program segments, that are a given. For example, we can use a constant for the sales price. If the price changes, we only have to change it in one place, where it was declared. Because it is a constant, we can be assured that the other parts of the code will not change the value of the constant. Check out the following constant EXAMPLE.

Server-side Includes

In server-side scripting, the constants are often defined in an external file, which is called a server-side include. Often it is useful to create a web page that contains only constants. The page is saved as an include page, with an .inc file extension. Then, the page that needs these constants can call this file using the keyword include with the following syntax:

<!--#include file = "PageWithConstants.inc"-->

One commonly used include file is ADOVBS.INC - which declares constants that are used when connecting a Web page to a database.

Arrays

An Array is an ordered group of related data items having a common variable name, all of the same data type. Arrays allow you to refer to a series of variables by the same name and to use a number (an index) to tell them apart. Arrays are quite useful since we can set up loops that deal efficiently with them.

Arrays can have a single dimension or multiple dimensions. A collection of variables is called a one-dimensional array. One-dimensional arrays are primarily use to hold lists.

To create an array, we assign a unique name to identify the collection of values. A single value in a one-dimensional array is called an element. Each element is referred to by its relative position within the array.

Declaring Arrays

To declare an array, we identify the name of the array and the type of data the array will store. In VBScript, we use the keyword dim, followed by the name of the array, followed by the number of elements in parentheses. In JavaScript, we use the keyword new in instead of the usual var keyword. The keyword new is used because the array is an object, and the new keyword instantiates a new array object. Since JavaScript is case sensitive, make sure to use the word Array and not array.

In VBScript, the syntax for declaring an array is:

        dim arrayName(NumberOfElements)

    For example, to declare an array called Products with 11 elements, we would write:

        dim Products(10)

In JavaScript, the syntax for declaring an array is:

        var arrayName = new Array(NumberOfElements)

    For example, to declare an array called Products with 11 items, we would write:

        var Products = new Array(10);

In these two examples, space is reserved in memory to hold the values. Each value is assigned to a position within the array, called an index. We use the index number to refer to individual elements in the array. The index of the array begins at zero and ends with the number of elements provided when the array was declared.

In both VBScript and JavaScript, unless otherwise explicitly stated, array indexes begin with zero. An array declared with a size of 10, actually has 11 elements or values.

Populating Arrays

Assigning values to elements in an array is called populating the array. To populate an array, specify the index number, and specify the value for each element with the following syntax:

VBScript:       ArrayName(IndexNumber)=Value
JavaScript:      ArrayName[IndexNumber]=Value;

JavaScript uses brackets instead of parentheses, and we add a semicolon at the end of JavaScript statements. Array elements can be used to store any valid data type.

The following sample code illustrates how to populate an array with six elements:

VBScript:
dim Products(6)
Products(0)="Pencils"
Products(1)="Pens"
Products(2)="Paper"
Products(3)="Markers"
Products(4)="Notepads"
Products(5)="Scissors"

JavaScript:
Var New Products(6);
Products[0]="Pencils";
Products[1]="Pens";
Products[2]="Paper";
Products[3]="Markers";
Products[4]="Notepads";
Products[5]="Scissors";

Using Array Elements

To retrieve the value of an array element, use the array name and the index number of the element. The value from the array is then available to be used in an expression, displayed in a Web page or placed into a variable. When an array element is used in an expression or assigned to a variable, the array element should appear on the right side of the assignment operator (=). To write the first element of an array to a Web page, use:

VBScript:
document.write Products(0)

JavaScript:
document.write(Products[0]);

CAREFUL: It is easy to mistype the JavaScript command since we need the brackets, parentheses and the semicolon.

Referencing an Array Object and Array Elements Using JavaScript

In JavaScript, there are two main methods used to reference the elements of an array. The example above used the name of the array and the index number of the element to refer to an element of the array. You could instead use an integer variable in place of the actual index value for the element.

In the sample code below, the array that is defined contains three elements (0,1,2). A variable, ProductIndex, is declared that will hold the value of the index number of the element. The array is populated with a value. The value of the element is retrieved using the array name (Products) and the value of the variable storing the index number (ProductIndex).

var Products=new Array(2);
var ProductIndex=1;
Products[1]="Pencils";
document.write(Products[ProductIndex]);

Because an array is an object, it has methods and properties. Any of the members of an object can be referred to by their name. The array object has several method including concat, join, reverse, slice, sort, toString and valueOf. An array also has several properties including constructor, prototype and length. Using the dot notation naming convention to refer to the length of the array object above, we can use  document.write(Products.length); in our script.

Obtaining Values From Form Elements

We can obtain the values entered by the user with the following syntax:

document.FormName.FormElementName.Checked for Radio Buttons or Check Boxes, OR USE

document.FormName.FormElementName.Value for Text Boxes, Text Areas, or Selection Lists.

Check out this EXAMPLE.