Previous Page TOC Next Page See Page



- 2 -
The JavaScript Language


Before you delve into the specifics of JavaScript programming—be it on a Web server or a Web browser—it's important to understand the basic syntax of a JavaScript program.

To this end, this chapter examines the following topics, which are generic to both Server and Client JavaScript:


Data Types and Variables


Unlike most high-level languages, which expect you to define or declare all variables before they are used, JavaScript adopts a more flexible approach to variable management.

To explain how variables work in JavaScript, this section first looks at how variables are defined, and then at the data types which can be stored by a variable. And then, finally it examines the literal values which can be assigned to a variable.

Variables


A variable is basically a user-defined container that can hold a value of some sort, be it a number, some text or something else. But unlike most high-level languages that force you to limit the contents of each variable to a specific type, JavaScript variables are said to be loosely typed language. This means that you don't need to specify the type of information a variable contains when the variable is created. In fact, the same variable can be assigned to data of different types depending on your requirements.

To declare a variable in a JavaScript program, you would write the following:

var variablename;

In this form, variablename is any unique name you choose, provided that it meets the following requirements. Variable names can consist of any combination of:

In addition, variables are case sensitive. This means a variable named Number and a variable named number are treated as separate containers.

The only other limitation placed on variable names is that you cannot use what are called reserved words as variables. Table 2.1 lists the current reserved words for JavaScript. Many of these may already be familiar to you as JavaScript commands, while others will be recognizable by people familiar with Java.

Table 2.1. JavaScript Reserved words.

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

Data Types


A variable in JavaScript can be assigned any type of value supported by the language definition. Currently, JavaScript recognizes five data types which are:

Numbers A number can be any value, be it an integer (1, 25, -133) or floating point (0.299, 20.26, -100.908).
Strings A string can represent any textual information such as: "Hello, my name is Wes Tatters."
Booleans A Boolean can be either true or false.


Note:

Unlike some other languages where Boolean values are represented by numbers such a 0 or 1, in JavaScript only true or false are acceptable.


nulls Null is a special statement that represents a null value. When you first declare a variable it is automatically assigned a value of null. (It is important to understand that a null value is different from a zero or an empty string.)
objects Objects are storage containers that hold both the value of a data element and any functions or methods that operate on that data. Chapter 3, "JavaScript and Object Oriented Programming," explores the concept and use of objects in detail.


To keep the JavaScript language simple and user friendly, there are no explicit int, short, float, double, long double or char data types. In addition, there is no mechanism for defining your own data types using typedef-like commands.


Literals


There are basically two ways that a variable can be assigned a value. It can be assigned at run-time based on some interaction by the user. (See Chapter 7, "Working with Forms" for more information.) Or it can be assigned by the programmer using what is called a literal.

In the most basic terms, a literal is a fixed value which can be assigned to a variable when a program is written. The following types of literals can be used in a JavaScript program.


Integers

An integer is a whole number such are 1,2,3,4,100 which can have either a positive or negative value. To assign an integer literal to a variable in a JavaScript program you would write something like the following:

var variablename = integer_literal;
 or

variblename = integer_literal;

In the first form, a new variable in defined and assigned a integer value, while in the second form an existing variable is assigned an integer value.



Tip:

The '=' sign placed between the variable and the integer_literal is called an assignment operator. See the "Expressions and Operators" topic later in the chapter for more detail.


In addition to the standard base 10 (Decimal) format, integer literals also can be written in either base 8 (Octal) or base 16 (Hex) format. Octal integers are indicated by placing a leading 0 in front of the number and Hex integers by placing a lead 0x in front of the number.

For example:

base10number = 10;
octalnumber = 012;
hexnumber = 0x0A;

Floating Points

A floating point literal can represent any number which is not considered a whole number or integer. That is, any number with a fractional component such as 1.2345 or -1.2345, or an exponential component like 12345E-4 or -12345E-4.

To assign a floating point literal to a variable in a JavaScript program you would write something like the following:

var variablename = float_literal;
 or

variblename = float_literal;


Caution:

In the current implementation of JavaScript, on certain computer platforms, floating point literals sometimes suffer from what are called floating point errors.

These errors sometimes result in a slight miscalculation of decimal values. This is, however, expected to be rectified before the release of Netscape Navigator 3.0.



Booleans

There are only two acceptable values for a Boolean literal. These are true or false. To assign a Boolean literal to a variable in a JavaScript program you would write something like the following:

var variablename = true;
 or

variblename = false;

Strings

A string literal is simply a string of zero or more characters surrounded by either single (') or double (") quotes. To assign a string literal to a variable you would write something like the following:

var stringname = "some text";
var stringname = 'some text';
or
stringname = "some text";
stringname = 'some text';


Note:

Be careful not to mix your single and double quotes when defining a string literal. If a literal starts with a double quote it must end with a double quote, and likewise for single quotes.



Escape Characters

When creating string literals, you may occasionally want to include characters in your string which have no physical representation. Such characters might include the backspace, tab, new line, or carriage return.

To represent these characters in a string literal, you first need to include a special character called the escape character. The escape character is represented by a backslash '\'. This tells JavaScript that the character following the backslash represents a special control character and not its actual value. Table 2.2 outlines the special characters currently supported by JavaScript.

Table 2.2. Escaped or Special Characters.

Escaped Character Description
\' insert a quote.
\" insert a double quote.
\b insert a backspace.
\f insert a form feed.
\n insert a new line character.
\r insert a carriage return.
\t insert a tab character.

Expressions and Operators


Once you have define a variable, you can assign new values to the variable, or work with the existing value using what are called operators and expressions.

This section examines what an expression is, and explains the wide variety of operators provided by JavaScript

What are Expressions


To quote from Netscape Communications online JavaScript guide, "An expression is any valid set of literals, variables, operators, and expressions that evaluates to a single value."

Cast your mind back to the first grade math and the question, "what is 1 + 1?". The statement '1 + 1' represents an expression. It describes a set of information which evaluates to a single value, which in this case is '2.'

'1 + 1' represents the most simple form of expression. It contains two integer literals which are added together using the arithmetic operator plus '+' (which are discussed in more detail later). This basic expression forms the basis of all other types of expression.

Assigned Expressions

To take this example one step further, look at the statement

result = 1 + 1;

This is also an expression. However, this time the result of the expression is explicitly assigned to the variable result using the assignment operator equals '='.

Expression Types

By using the various operators described later in this section, you can create three different types of expression in JavaScript. These types are:

Arithmetic Expressions Any expression which evaluates to a number is considered an arithmetic expression.
Logical Expressions These are a special group of expressions that evaluate to either a true or false result.
String Expressions A string expression can be used to add strings together. It evaluates to a new string.

Conditional Expressions

There is a special type of expression provided by JavaScript called a conditional expression. A conditional expression is one which can evaluate to one of two different results depending on a user defined condition. A conditional expression takes the form.

condition ? expression1 : expression2

Condition is a logical expression that must evaluate to either true or false. If the condition evaluates to true then the entire expression evaluates to expression1. If the condition evaluates to false then the entire expression evaluates to expression2.

Supported Operators


In their most basic state, all expressions take the same general form:

left_operand operator right_operand

Each operand can be either a variable or literal value, depending on the type of expression and the type of operator that controls the expression.

Table 2.3 outlines all of the operators that can be used in JavaScript expressions. In this table the operators are grouped by the following types:

Arithmetic Operators Arithmetic operators take numeric literals or numeric variables as their operands and return a numerical value.
Bitwise Operators Bitwise operators treat their operands as a set of binary bits (zeros and ones). They perform operations on this binary representation, then return the result as a numeric values.
Logical Operators Logical operators work with Boolean (logical) values and they return a Boolean value. (Booleans use only true and false values.)
Comparison Operators Comparison operators compare the values of their operands and return a Boolean value. This Boolean value indicates if the result of the comparison was true or not true (false).
String Operators String operators take string values in their operands and return a string value as the result.
Assignment Operator Assignment operators assign a new value to their left operand based on the value of their right operand. The only limitation placed on this type of expression is that the left operand cannot be literal.

Table 2.3. Summary of JavaScript operators.

Name of Operator Syntax Result
Arithmetic Operators
Addition x + y Adds x and y
Subtraction x - y Subtracts y from x
Multiplication x * y Multiplies x by y
Division x / y Divides x by y
Modulus x % y Evaluates to the remainder when dividing x by y.
Preincrement ++x Adds one to x
Postincrement x++ Evaluates to x then adds 1 to the value of x
Predecrement --x Subtract one from x
Postdecrement x-- Evaluates to x then subtracts 1 from the value of x
Unary negation -x Negates the value of x
Bitwise Operators
Bitwise AND x & y AND's the binary representation of x and y
Bitwise OR x | y OR's the binary representation of x and y
Bitwise XOR x ^ y Exclusive OR's the binary representation of x and y
Left Shift x << y Shifts bits in the binary representation of x, y positions to the left. Zero value bits are shifted in from the right.
Sign-propagating x >> y Shifts bits in the binary
Right Shift
representation of x, y positions to the right. Value of left-most bit is shifted in from the left.
Zero-fill Right Shift x >>> y Shifts bits in the binary representation of x, y positions to the right. Zero value bits are shifted in from the left.
Logical Operators
And exp1 && exp2 Evaluates to true if exp1 and exp2 both evaluate to true.
Or exp1 || exp2 Evaluates to true if either exp1 or exp2 evaluate to true.
Not !exp1 Evaluates to true if exp1 is not true.
Comparison Operators
Equals x == y Returns true if x is equal to y.
Not equal x != y Returns true if x is not equal to y.
Less than x < y Returns true if x is less than y.
Less than or equal to x <= y Returns true if x is less than or equal to y.
Greater than x > y Returns true if x is greater than y.
Greater than or equal to x >= y Returns true if x is greater than or equal to y.
String Operators
Concatenation x + y concatenates string x and string y together.
Assignment Operators
Equal x = y Assigns the value of y to x
Compound Arithmetic x += y Adds y to x and assigns the result to x.

x -= y Subtracts y from x and assigns the result to x.

x *= y Multiplies x by y and assigns the result to x.

x /= y Divides x by y and assigns the result to x.

x %= y Takes the Modulus of x and y and assigns the result to x.
Compound Bitwise x &= y AND's the binary representation of x and y and assigns the result to x.

x |= y OR's the binary representation of x and y and assigns the result to x.

x ^= y Exclusive OR's the binary representation of x and y and assigns the result to x.

x <<= y Shifts bits in the binary representation of x, y positions to the left. Zero value bits are shifted in from the right and assign the result to x.

x >>= y Shifts bits in the binary representation of x, y positions to the right. Value of left-most bit is shifted in from the left and assign the result to x.

x >>>= y Shifts bits in the binary representation of x, y positions to the right. Zero value bits are shifted in from the left and assign the result to x.

Operator Precedence


When you combine more than one operator in a expression, the precedence of operators rule determines the order in which they are applied when evaluating an expression.

The precedence of operators for JavaScript , from highest to lowest is as follows:

call, member () [] .
negation/increment ! ~ - ++ --
multiply/divide * / %
addition/subtraction + -
Bitwise shift << >> >>>
relational < <= > >=
equality == !=
bitwise-and &
bitwise-xor ^
bitwise-or |
logical-and &&
logical-or ||
conditional ?:
assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
comma ,

When calculating the value of an expression any operators higher up the precedence list are evaluated before those lower on the list. In most situations this order is acceptable, however, you can override the order using parentheses when needed.

For example, '10 + 10 * 10 + 10' evaluates to 120 using the normal order of precedence rules because '10 * 10' is evaluated first. But by using parentheses, as in '( 10 + 10 ) * ( 10 + 10 )' the result is 400 because the two '10 + 10' expressions are forced to evaluate first.

Programming Commands


Regardless of what language you use, a program is simply a set of instructions that describe to a computer some action, or group of actions, you want it to perform. In the most basic case, this set of instructions starts at the beginning of a list of code and works through each instruction in the list one at a time until it reaches the end:

<SCRIPT LANGUAGE="JavaScript">
// start of program - NOTE: lines that start with '//' are treated as comments
document.write( "step one") ;
document.write( "step two") ;
// end of program
</SCRIPT>


Note:

document.write() is a method associated with the document object in Client JavaScript. It is used to send text to a Web page. Chapter 5, "The Netscape Navigator Object Tree," discusses its use and syntax in detail.


You will rarely want a program to proceed straight through a list of steps—especially in JavaScript—because it would be easier to write the messages on the screen using HTML than to code them by using JavaScript. For this reason, most programming languages include a basic set of instructions that enable you to control the flow of the instructions.

The final section of this chapter examines each of the basic commands and statements included in the JavaScript language and discusses the reasons from their use.

Comments


The first command is not so much a programming command as the lack of one. Comments are used in a JavaScript program to insert messages and other information that you don't actually want to be executed.

By placing // before any text on a line of JavaScript code you indicate that any text following it should be treated as comments. Alternatively, if you want to enter a number of lines of comments, simply surround the lot with /* your comments go here */.

/* This comment can be spread
 over a number of lines */
// This is a comment on a single line
var number = 1; // this is also a comment

Statement Blocks


A statement block is a group of statements or programming commands that have been surrounded by a pair of braces {. . .}. You can use a statement block anywhere in your JavaScript program that a single command would normally be placed, as shown here:

{
 Place as many lines of code ;
 as you need inside the statement block ;
}

For the most part, you only used statement blocks in combination with other commands which are discussed later in the chapter.

The Semicolon


In JavaScript, the semicolon ';' has a special purpose. It is used as a separator between program statements. By using a semicolon the following line of code is totally acceptable:

var num1 = 1 ; var num2 = 3 ; var num3 = num1 + num2 ;

When JavaScript encounters this line, it uses the semicolons to indicate where each new statement starts and the old one ends. In fact, as far as JavaScript is concerned, the previous line of code is no different from the following:

var num1 = 1 ;
var num2 = 3 ;
var num3 = num1 + num2 ;


Note:

The current version of Client JavaScript does not require a semicolon after each statement if they are placed on separate lines. For consistency's sake, however, it is good practice to include them.



var Revisited


The var statement was introduced during the discussion of variable declarations earlier in this chapter. The purpose of the var statement is to indicate the declaration of a new variable. For example:

var somevariable = "some value";

This declares a new variable and stores the string literal "some value" inside it.



Note:

The current version of JavaScript does not actually require the use of the var statement at all. In fact, if you use a variable name that has not been declared previously, JavaScript automatically declares it. Having said that, this may change in the future, so it is a good idea to use the var statement for all new variable declarations.



Conditional Tests


One of the most common actions performed by most computer programs is the conditional execution of program code depending on the prevailing situation when the program is run.

By using conditional commands you can control, if and when commands or blocks of commands are executed.

The if Statement

The first instruction used for this purpose is called the if statement. It enables you to perform tests inside program code to determine which parts of the program should be run under any given situation. The basic syntax of the if statement is

if ( logical expression ) statement;

For example, assume that you have a Web site that asks whether a person is male or female. In such cases, you might want to respond to the person using a gender-specific response, based on the indicated sex:

if ( Sex == "male" ) document.write("Thank you for your response, Sir" ) ;
if ( Sex == "female" ) document.write("Thank you for your response, Madam" ) ;

If this piece of code were run and the variable Sex had been assigned a value of "male", the first document.write() method would be called. If it had been assigned a value of "female", the second statement would be displayed.

The logical expression next to the if statement performs a comparison between the variable Sex and the word "male". This comparison is controlled by what are called comparison operators. In this case, a test for equivalence was performed as signified by the == symbol. Table 2.3, discussed previously, lists the comparison operators currently recognized by JavaScript.

The previous code also could have been written using the statement block parentheses discussed earlier in this chapter. In such a case the statement section of the if command would be replace by a statement block as shown here:

if ( Sex == "male" ) {
 document.write("Thank you for your response, Sir" ) ;
}
if ( Sex == "female" ) {
 document.write("Thank you for your response, Madam" ) ;
}

if. . .else

The preceding example also could have been written in a slightly different way, by using a different version of the if statement that incorporates an else statement:

if ( Sex == "male" ) {
 document.write("Thank you for your response, Sir" ) ;
} else {
 document.write("Thank you for your response, Madam" ) ;
}

In this example, because there is no need for a second if test—because a person can be only male or female—the else statement was used to tell the program to display the second message if the first test failed.



Note:

In both of the preceding examples, any number of statements could be assigned to each outcome by including each statement inside the appropriate set of braces.



Looping Statements


On occasion, you will want a group of statements to run multiple times rather than just once. Two looping statements are supported by JavaScript to carry out this task. The first kind of statement, called a for loop, is ideal for situations in which you want a group of instructions to occur a specified number of times. And the second kind, the while loop, is better suited to situations in which the number of loops required is to be determined by an outside source.

for Loops

The basic structure of a for loop looks like this:

for (var count = 1; count <= 10; ++count ) {
 your statements go here ;
}

In this example, a variable called count is declared and set to a value of 1. Then a test is made to see whether the value of count is less than or equal to 10. If it is, all the statements inside the braces, {}, following the for statement, are executed once. Then, the value of count is incremented by 1 by the statement ++count, and the count <= 10 test is performed again. If the result is still true, all the instructions inside the braces are executed again. This process then proceeds until the value of count is greater than 10, at which point the for loop ends.

while Loops

The basic structure of a while loop looks like the following:

while ( logical expression ) {
 your statements go here ;
}

Unlike the for loop, which has a built-in increment mechanism, the only test required for a while loop is a true result from the logical expression or condition test following the while statement. This test could be an equivalence test, as in a == b, or any of the other tests mentioned previously in the if statement.

As long as this condition tests true, the statements inside the braces following the while loop continue to run forever—or at least until you close your Web browser.



Caution:

When using while loops, you need to avoid creating loops that never end. (Such a loop is known as an infinite loop.) If you do manage to create an endless loop, about the only option you have to halt the loop is to shut down the Web browser or Web server.



break

When working with for and while loops, you will sometimes encounter situations where you need to terminate the loop prematurely. The easiest way to do this is by using the break statement, as shown here:

while ( true ) {
 Some code;
 if ( sometest ) break;
 Some other code;
}

When a program encounters a break statement while executing a for or while loop, the loop is terminated immediately and program execution moves to the first command following the loop.

continue

The continue statement works similarly to the break statement. Instead of terminating the loop entirely, the continue statement terminates the current iteration of the loop:

for ( var count = 1; count < 100 ; count++ ) {
 Some code ;
 if ( sometest ) continue ;
 Some other code ;
}

When a program encounters a continue statement while executing a for or while loop, the current pass through the loop is terminated, ignoring additional commands. Program execution moves back to the first statement of the loop.

Functions


The final programming element for this chapter is that of functions. In many programming languages, including JavaScript, functions—and their object oriented relative the method—represent the basic building block for expanding the functionality of the language.

Basically, functions are small blocks of program code that can be called by other parts of a program. There are two types of functions supported in JavaScript—pre-defined functions and user defined functions.

Pre-defined functions have been built in the JavaScript language, while user-defined functions are created by JavaScript programmers like yourself.

Defining a Function

To define a function for a JavaScript program, you write something like the following:

<SCRIPT LANGUAGE="JavaScript">
function functionName( operands ) {
 The actions to be performed by your function go here ;
}
</SCRIPT>

functionName is any unique name you choose, and operands is a list of any values or variables you want to hand to the function. Following the function definition and inside the set of braces, { }, you include the list of instructions you want the function to perform. These could be a set of calculations, validation tests for a form, or just about anything else you can think of.



Note:

JavaScript also includes a set of built-in objects and functions that enable you to perform mathematical operations, string manipulation, and date and time calculations. Many of these functions are examined in Chapter 4, "General Objects and Functions."



The Return Statement

The return statement is used in conjunction with a function definition to stop the execution of the function and return program control to the program code that called the function in the first place. The syntax for the return statement follows:

return expression;

Expression can be any value. The contents of expression are return to the calling program as the value of the function.

Using Functions

Once a function has been defined for a JavaScript program, it can then be called from anywhere else in the program, in the same way that you use JavaScript's built in commands. Take for example the following function definition:

function add( op1, op2 ) {
 return ( op1 + op2 );
}

In this code a function called add() is defined with two operands called op1 and op1. These are the variables which receive values sent from some calling program code. In the add() function, the contents of the op1 and op2 variables are added together. The result is handed back from the function to the called program using the return statement.

By including the add() function definition as a part of a JavaScript program you make it available for use anywhere within the current Web page. Take for example the following program:

<SCRIPT LANGUAGE="JavaScript">
//The function definition starts here
function add( op1, op2 ) {
 return ( op1 + op2 );
}
//The JavaScript program code starts here
var num1 = 50;
var num2 = 25;
var answer = 0;
answer = add( num1, num2 ); // this line calls the function add()
document.write( answer );
</SCRIPT>

With the add() function defined at the top of the program, it can simply be used as though it was an expression, because it evaluates to a result.



Note:

Unlike some other languages, there is no physical requirement covering where in your program code function definitions should be placed. However, many programmers find that declaring all their JavaScript functions at the top of a Web page makes for easier code management.



Variable Scope

When you begin to deal with functions, you need to be aware of a new facet to variables.

As a rule, any variables that you declare inside a JavaScript program are automatically available through out the entire program. Such variables are said to be global variables. However, when you declare a variable inside a function, that variable is only available inside the function itself. Such a variable is said to be a local variable.

Summary


Despite the fact that JavaScript is a relatively simple language in both syntax and variable definition, it provides enough powerful capabilities to handle all but the most complex of Web publishing needs.

Its true power, does not, however, lie in its seemingly limited command set or data types, but in the object-based framework that surrounds it. The principals behind this object-based structure are examined in Chapter 3, "JavaScript and Object Oriented Programming."

Previous Page Page Top TOC Next Page See Page