Chapter 7 Core Language

This chapter is a detailed reference of all the items and elements that make up the core JavaScript and JScript languages as well as information in the ECMA-262, 3rd Edition standard (ECMAScript). Because the details of JavaScript, JScript, and ECMAScript varies slightly, so does each one’s definition of core. Because of these variations, this chapter covers items that are considered core in one standard, but might not exist in the other standards. Every nuance of the languages is covered, giving you a one-stop place to get answers to all your questions. Each entry includes version, environment support, syntax, a description, and an example, as well as many other details.

The chapter is in alphabetical order, by objects, to provide you with quick, easy access to the major parts of the language. The methods, properties, functions, and event handlers of every object appear alphabetically after the respective parent object, using the simple dot notation that makes the language so easy to learn. For example, the sin() function is found after the Math object as Math.sin().

@_alpha

JScript3.0+

IE 4+

Syntax

@_alpha

Description

The @_alpha variable is used in JScript conditional compilation to determine if a DEC Alpha processor is being used. When the variable is not true, it behaves as NaN although it is technically undefined.

Example

Listing 7.1 alerts the user when a DEC Alpha processor is used.

Listing 7.1 Detect a DEC Alpha Processor

<script type="text/jscript" language=“JScript”>
<!--
@if (@_alpha)
 alert("You are using a DEC Alpha processor.");
@else
 alert("You are NOT using a DEC Alpha processor.");
@end

// -->
</script>

@_jscript

JScript3.0+

IE 4+

Syntax

@_jscript

Description

The @_jscript variable is used in JScript conditional compilation to determine if JScript is being used. This variable is always true.

Example

Listing 7.2 displays an alert box based on the value of the @_jscript variable.

Listing 7.2 Detect a JScript

<script type="text/jscript" language=“JScript”>
<!--
@if (@_jscript)
 alert("The @ jscript variable is true.");
@else
 alert("The @_jscript variable is NOT true.");
@end

// -->
</script>

@_jscript_build

JScript3.0

IE 4+

Syntax

@_jscript_build

Description

The @_jscript_build variable is used in JScript conditional compilation to hold the build number of the JScript scripting engine.

Example

Listing 7.3 uses the @_jscript_build variable to display the build number of the JScript engine that is being used.

Listing 7.3 Retrieve JScript Build Number

<script type="text/jscript" language=“JScript”>
<!--

//Set conditional compilation so @_jscript_build variable will be defined.
@cc_on

//Display the JScript build number using the @_jscript_build variable.
document.write("The JScript engine build number is ",@_jscript_build);

// -->
</script>

@_jscript_version

JScript3.0+

IE 4+

Syntax

@_jscript_version

Description

The @_jscript_version variable is used in the JScript conditional compilation to hold the JScript version number in major.minor format.

Example

Listing 7.4 uses the @_jscript_version variable to display the JScript version that is being used.

Listing 7.4 Determine JScript Version

<script type="text/jscript" language=“JScript”>
<!--
//Set conditional compilation so @_jscript_version variable will be defined.
@cc_on
//Display the JScript verision number using the @_jscript_version variable
document.write("The JScript version is ",@_jscript_version).
// -->
</script>

@_mac

JScript3.0+

IE 4+

Syntax

@_mac

Description

The @_mac variable is used in JScript conditional compilation to determine if an Apple Macintosh system is being us ed. When the variable is not true, it behaves as NaN although it is technically undefined.

Example

Listing 7.5 alerts the user when an Apple Macintosh system is used.

Listing 7.5 Detect an Apple Macintosh System

<script type="text/jscript" language=“JScript”>
<!--

@if (@_mac)
 alert("You are using an Apple Macintosh system.");
@else
 alert("You are NOT using an Apple Macintosh system.");
@end

// -->
</script>

@_mc680x0

IE 4+

JScript3.0+

Syntax

@_mc680x0

Description

The @_mc680x0 variable is used in JScript conditional compilation to determine if a Motorola 680×0 processor is being used. When the variable is not true, it behaves as NaN although it is technically undefined.

Example

Listing 7.6 alerts the user when a Motorola 680x0 processor is used.

Listing 7.6 Detect a Motorola 680x0 Processor

<script type="text/jscript" language=“JScript”>
<!--

@if (@_mc680x0)
 alert("You are using a Motorola 680x0 processor.");
@else
 alert("You are NOT using a Motorola 680x0 processor.");
@end

// -->
</script>

@_PowerPC

IE 4+

JScript3.0+

Syntax

@_PowerPC

Description

The @_PowerPC variable is used in JScript conditional compilation to determine if a Motorola PowerPC processor is being used. When the variable is not true, it behaves as NaN although it is technically undefined.

Example

Listing 7.7 alerts the user when a Motorola PowerPC processor is used.

Listing 7.7 Detect a Motorola PowerPC Processor

<script type="text/jscript" language=“JScript”>
<!--

@if (@_PowerPC)
 alert("You are using a Motorola PowerPC processor.");
@else
 alert("You are NOT using a Motorola PowerPC processor.");
@end

// -->
</script>

@_win16

IE 4+

JScript3.0+

Syntax

@_win16

Description

The @_win16 variable is used in JScript conditional compilation to determine if a win16 system is being used. When the variable is not true, it behaves as NaN although it is technically undefined.

Example

Listing 7.8 alerts the user when a win16 system is used.

Listing 7.8 Detect a win16 System

<script type="text/jscript" language=“JScript”>
<!--

@if (@_win16)
 alert("You are using a 16 bit Windows system.");
@else
 alert("You are NOT using a 16 bit Windows system.");
@end

// -->
</script>

@_win32

JScript3.0+

IE 4+

Syntax

@_win32

Description

The @_win32 variable is used in JScript conditional compilation to determine if a win32 system is being used. When the variable is not true, it behaves as NaN although it is technically undefined.

Example

Listing 7.9 alerts the user when a win32 system is used.

Listing 7.9 Detect a win32 System

<script type="text/jscript" language=“JScript”>
<!--

@if (@_win32)
 alert("You are using a 32 bit Windows system.");
@else
 alert("You are NOT using a 32 bit Windows system.");
@end
// -->
</script>

@_x86

JScript3.0+

IE 4+

Syntax

@_x86

Description

The @_x86 variable is used in JScript conditional compilation to determine if a Intel processor is being used. When the variable is not true, it behaves as NaN although it is technically undefined.

Example

Listing 7.10 alerts the user when an Intel processor is used.

Listing 7.10 Detect an Intel Processor

<script type="text/jscript" language=“JScript”>
<!--

@if (@_x86)
 alert("You are using an Intel processor.");

@else
 alert("You are NOT using an Intel processor.");
@end

// -->
</script>

@cc_on

JScript3.0+

IE 4+

Syntax

@cc_on

Description

The @cc_on statement is used to activate JScript conditional compilation in the scripting engine.

Example

Listing 7.11 shows where the @cc_on statement would be used within JScript code to get the JScript version.

Listing 7.11 Activate Conditional Compilation

<script type="text/jscript" language=“JScript”>
<!--

//Set conditional compilation so @_jscript_version variable will be defined.
@cc_on

//Display the JScript version number using the @_jscript_version variable
document.write("The JScript version is",@_jscript_version).

// -->
</script>

@if

JScript3.0+

IE 4+

Syntax

@if (condition1)
 statement1
@elif (condition2)
 statement2

@else
 statement3
@end

Description

The @if statement operates much the same as a typical if conditional statement, but it evaluates compiled variables and has a slightly different syntax. If the expression in condition1 evaluates to true, statement1 is executed. Otherwise, the condition2 is evaluated to determine whether statement2 should be evaluated. The @elif statement operates the same as the JavaScript else…if statement, even though it looks different. You can use as many @elif statements as needed or none at all. Only one @else statement should be used to catch conditions that don’t meet any of the previous conditionals. Similar to the @elif statement, the @else statement is optional. The @end statement is required at the end of all @if conditionals.

Example

Listing 7.12 displays a message based on the type of processor being used.

Listing 7.12 Using @if to Display Processor Type


<script type="text/jscript" language=“JScript”>
<!--

//Alert the user as to which type of processor they are using.
@if(@_jscript)
     alert("You are using a DEC Alpha processor.");
@elif(@_mc680x0)
     alert("You are using a Motorola 680x0 processor.");
@elif(@_PowerPC)
     alert("You are using a Motorola PowerPC processor.");
@elif(@_x86)
     alert("You are using an Intel processor.");
@else
     alert("I don’t know what type of processor you have!");
@end

// -->
</script>

@set

JScript3.0+

IE 4+

 

Syntax

@set @varName = value

Description

The @set property allows the creation of JScript variables. The name of the variable must start with an ampersand character. If the variable is used before being defined, its value will be NaN.

Example

Listing 7.13 uses the @set property to create a custom compiled variable called @number and assigns the number 25 to the variable. The variable is then used to display a sentence in the browser.

Listing 7.13 Create Custom Compiled Variable Using the @set Property


<script type="text/jscript" language=“JScript”>
<!--

//Create a custom compiled variable called @number and set it to 25
@set @number = 25.

//Display a sentence in the browser based on the value stored in the
//custom compiled variable @number.
@if(@number == 25)
     document.write("Number is equal to ",@number);
@else
     document.write("Number is not equal to 25.");
@end

// -->
</script>

Operators

- (Subtraction)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1 - num2

Description

The number to the right of the operator is subtracted from the number to the left of the operator. If either operand is a string, an attempt is made to convert the string to a number before performing the operation.

Example

The code in Listing 7.14 creates a string out of the number “45”. The string is converted to a number before being subtracted from the number 25. The result of the subtraction operation (20) is displayed.

Listing 7.14 Using the Subtraction Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

//Declare the number 45 as a string
aString = new String(“45”);

//Subtract 25 from 45
answer = aString - 25;
document.write("answer = (45-25)<br>");

//Answer is equal to 20
document.write("answer = ",answer);

// -->
</script>

- (Unary Negation)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

-num

Description

The unary negation operator changes the sign of num. When negating a variable, the contents of the variable do not change; only the value returned is negated. If the operand is a string, it is converted to a number before performing the unary negation operation.

Example

The code in Listing 7.15 creates a string “36”. The string is converted to a number before being negated. The result of the negation is -36.

Listing 7.15 Using the Negation Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

//Declare the number 36 as a string
aString = new String(“36”);

//negate the number
answer = -aString;
document.write("answer = -aString<br>");
//Answer is equal to -36
document.write("answer = ",answer);

// -->
</script>

-- (Decrement)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

--variable
variable--

Description

The pre-decrement operator, defined in the first syntactical definition, decrements variable by 1. The new decremented value is returned by the operation.

The second syntactical definition contains the post-decrement operator. This operator is similar to the pre-decrement operator in that it decrements variable by 1. However, the original value is returned by the operation before being decremented.

In both cases, if the operand is a string, it is converted to a number before performing the operation.

Example

Listing 7.16 demonstrates how the pre-decrement and post-decrement operators work. Notice that the variable num holds a string that is converted before performing the decrement operations. The result from executing this code is shown in Figure 7.1.

Listing 7.16 Using the Decrement Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

// Store value in variable before pre-decrement
document.write("<h3>Before Pre-decrement</h3>");
num = new String(“807”);   //num holds the string 807
document.write("num=",num,"<br>");   //807 is displayed.

// Pre-decrement the value stored in num
returnValue = --num;
document.write("<h3>After Pre-decrement</h3>");
document.write("num=",num,"<br>");  //806 is displayed.

//806 is displayed by returnValue
document.write("Value returned from operation is ",returnValue,"<br>");
// Post-decrement the value stored in num
returnValue = num--;
document.write("<h3>After Post-decrement</h3>");
document.write("num=",num,"<br>");    //805 is displayed.

//806 is displayed by returnValue
document.write("Value returned from operation is ",returnValue,"<br>");

// -->
</script>

Figure 7.1 The difference between pre-decrement and post-decrement.

Image

! (Logical NOT)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

!operand

Description

The ! operator inverts the boolean value returned from the !operand. So, if operand evaluates to true, the result of the operation is false. If the operand evaluates to false, the result is true. When the operand evaluates to a non-Boolean value, it is converted to true or false before performing the inversion.

Example

In Listing 7.17 the character “1” is converted to the Boolean true before inverting the value with the NOT operand. The variable theReverseTruth is assigned false.

Listing 7.17 Using the Logical NOT Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

//Create a variable that contains 1
theTruth = new String(“1”);

//Invert the value stored in the previous variable
theReverseTruth = !theTruth;

//Output the values stored in the two variables
document.write("theTruth = ",theTruth,"<br>");
document.write("theReverseTruth = ",theReverseTruth);

// -->
</script>

!= (Not Equal)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

expression1  != expression2

Description

The not equal operator compares the first expression to the second expression. If the expressions are not equal, true is returned from the operation. If they are equal, false is returned.

JavaScript and Microsoft JScript interpreters attempt to convert the expressions to the same data type before evaluating the not equal operation using the following rules:

true is converted to the number 1, and false is converted to zero before being compared.

• If either of the operands is NaN, the equality operator returns false.

• Null and undefined are equal.

• Null and undefined are not equal to 0 (zero), "" (empty string), or false.

• If a string and a number are compared, attempt to convert the string to a number and then check for equality.

• If an object and a string are compared, attempt to convert the object to a string and then check for equality.

• If an object and a number are compared, attempt to convert the object to a number and then check for equality.

• If both operands of an equality operation are objects, the address of the two objects are checked for equality.

Example

In the following example, the string “523” is converted to a number (except in JavaScript 1.2, in which type conversion is not performed), so that two numbers are compared. Because the left operand is equal to the right operand, the phrase "The string 523 is EQUAL to the number 523" is written to the browser window.

Listing 7.18 Using the Not Equal Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

//Before comparing this string to the number the
//string will be converted to a number.
if(“523” != 523)
{
    //If the two numbers are not equal then display this sentence.
    document.write("The string 523 is NOT equal to the number 523");
}
else
{
    //If the two numbers are equal then display this sentence.
    document.write("The string 523 is EQUAL to the number 523");
}

// -->
</script>

!== (Non-Identity)

JavaScript 1.3+, ECMAScript 3E+, JScript 1.0+

Nav4.06+, IE 3+, Opera5+

 

Syntax

expression1  !== expression2

Description

The non-identity operator compares the first expression to the second expression. If the value on the left is not equal to the value on the right side of the operator, true is returned from the operation. If the values are equal, false is returned.

Example

In Listing 7.19, the string “8765” is NOT converted to a number, so the two expressions are not the same type. Because the two operands are not the same type, they are not equal, so the phrase "The string 8765 is NOT equal to the number 8765" is written to the browser window.

Listing 7.19 Using the Not-Identity Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

//Compare the string to the number but do not
//convert the string to a number.
if(“8765” !== 8765)
{
    //If the string and number are not equal then display this sentence.
    document.write("The string 8765 is NOT equal to the number 8765");
}
else
{
    //If the string and number are equal then display this sentence.
    document.write("The string 8765 is EQUAL to the number 8765");
}

// -->
</script>

% (Modulus)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1  % num2

Description

The modulus operator begins the same as the division operator, by dividing the left value by the right; but instead of returning the normal result of division, only the remainder is returned by the operation. If either operand is a string, an attempt is made to convert the string to a number before performing the operation.

Example

In Listing 7.20, the variable answer is assigned the value 1 because 7 is divided by the number 2 three times plus a remainder of 1. This remainder is stored in the variable answer.

Listing 7.20 Using the Modulus Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

//1 is stored in the variable answer.
answer = 7 % 2;

//Display the value in the variable answer
document.write("answer = ",answer);

// -->
</script>

%= (Modulus Assignment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

variable %=  value

Description

The modulus assignment operator divides the value stored in the left variable by the right value. The remainder is returned by the operation and stored in the variable to the left of the operator. If value is a string, an attempt is made to convert the string to a number before performing the modulus and assignment.

Example

In Listing 7.21, the variable answer is initially assigned the value 17. The number 17 is divided by the number 3. The remainder portion (modulos) of the result of the division is stored in the variable answer, overwriting the number 3.

Listing 7.21 Using the Modulus Assignment Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

//Initialize the variable answer with 3.
answer = 17;

//The number 2 is stored in the variable answer.
answer %= 3;

//Display the value stored in the variable answer.
document.write("answer = ",answer);

// -->
</script>

& (Bitwise AND)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1 &  num2

Description

The bitwise AND operator looks at the integer numbers on both sides of the operator as 32-bit binary numbers. The bitwise AND (&) operator individually evaluates each of the 32 bits representing the number on the left of the operator to the corresponding bit of the number on the right of the operator using the truth table shown in Table 7.1. The 32-bit binary result of the logical AND operation is converted to an integer value and returned from the bitwise AND operation.

Table 7.1 Bitwise AND Truth Table

Image

Example

The code in Listing 7.22 uses the bitwise AND operator on the numbers 11 and 6. The result of the bitwise AND operation is 2.

Listing 7.22 Using the Bitwise AND Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

// integer = 32-bit binary representation
// 11&#160;= 00000000000000000000000000001011
//  6 = 00000000000000000000000000000110
//  2 = 00000000000000000000000000000010

// answer is equal to 2
answer = 11 & 6;

//Display the value stored in the variable answer.
document.write("11 & 6 = ",answer);

// -->
</script>

&& (Logical AND)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

expression1 &&  expression2

Description

The logical AND operator returns true if the expression on the left and the expression on the right of the operator evaluate to true. If either the left, right, or both evaluates to false, the result of the operation is false.

Be sure to note that the implementation of the logical AND operator in JavaScript is more complex than what was just mentioned. The AND operation begins by evaluating the left expression. If the left expression evaluates to false, the basic logic of the AND operator is complete, so the right expression is never evaluated. But if the left expression evaluates to true, the right expression must be evaluated to determine the final result of the AND operation. In either case, the final result returned by the AND operation is actually determined by the result of the last expression to be evaluated.

Example

Listing 7.23 demonstrates the complications associated with the logical AND operator. The first expression evaluates to false, causing the logical AND operation to evaluate to false and the message "The && evaluated FALSE!" is displayed. Because the first expression evaluates to false, the second expression, which assigns the number 5 to the variable x, is not evaluated and x remains equal to 3.

Listing 7.23 The Complicated Logical AND Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

//Initialize the variable x with the number 3.
x = 3;

//The assignment of 5 to the variable x never occurs
//since the expression (2==x) evaluates to false in the if statement.
if((2==x) && (x=5))
{
    document.write("The && evaluated TRUE!<br=");
}
else
{
    document.write("The && evaluated FALSE!<br>");
}

// x is still equal to 3
document.write("x=",x,"<br>");

// -->
</script>

&= (Bitwise AND Assignment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

Syntax

variable &=  value

Description

The bitwise AND plus assignment operator looks at the integer numbers on both sides of the operator as 32-bit binary numbers. The bitwise AND (&) operator individually evaluates each of the 32 bits representing the number on the left of the operator to the corresponding bit of the number on the right of the operator using the truth table shown in Table 7.2. The 32-bit binary result of the bitwise AND operation is converted to an integer value and stored in the variable to the left of the operator.

Table 7.2 Bitwise AND Truth Table

Image

Example

In Listing 7.24, the bitwise AND plus assignment operator is used on the numbers 12 and 6 to generate a result of 4.

Listing 7.24 Using the Bitwise AND Plus Assignment Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

// integer = 32-bit binary representation
// 12 = 00000000000000000000000000001100
//  6 = 00000000000000000000000000000110
//  4 = 00000000000000000000000000000100

//Initialize the variable x with the number 6.
x = 6;

//x is now equal to 4.
x &= 12;

//Display the value stored in the variable x.
document.write("x = ",x);

// -->
</script>

* (Multiplication)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1 *  num2

Description

The multiplication operator (*) multiplies the left operand by the right operand. If either of the operands is a string, an attempt is made to convert the string to a number.

Example

In Listing 7.25, the string “5” is converted to a number before being multiplied by the number 6. The result of 30 is displayed in the browser window.

Listing 7.25 Using the Multiplication Operator

<script type=“text/javascript” language=“JavaScript”>
<!--

//Initialize the variable aString.
aString = new String(“5”);

//Perform mulitplication operation.
x = aString * 6;
document.write("x = ",x);

// -->
</script>

*= (Multiplication Assignment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

variable *= value

Description

The number stored in the variable to the left of the operator is multiplied by the number to the right of the operator. The result of the multiplication is written into the variable to the left of the operand. If either of the operands is a string, it is converted to a number.

Example

In Listing 7.26, the string “5” is converted to a number before being multiplied by the number 7. The result of the multiplication, which is 35, is stored in the variable x.

Listing 7.26 Using the Multiplication Plus Assignment Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

//Initialize the variable x with the number 7
//and the variable aString with “5”.
x = 7;
aString = new String(“5”);

//Perform mulitplication and assignment operation.

//Display the value stored in the variable x.
document.write("x = ",x);

// -->
</script>

, (Comma)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, IE 3+, Opera3+

 

Syntax

expression1,   expression2,…,expressionN3

Description

The comma allows multiple expressions to be evaluated as one expression. The only value returned from this operation is the return value of the right-most expression.

Example

In Listing 7.27, the comma is used to execute multiple assignment statements on one line. The number 3 is stored in y, and then 9 is stored in z. Because z=9 is the last statement in the group of comma-separated statements, its value is returned and stored in the variable x. The final values stored in each variable is displayed (x=9, y=3, z=9).

Listing 7.27 Using the Comma to Separate Multiple Statements


<script type=“text/javascript” language=“JavaScript”>
<!--

//Assign values to all three variables.
x = (y = 3, z = 9);

//Display the values stored in all three variables.
document.write("x = ",x,"<br>y = ",y,"<br>z = ",z);

// -->
</script>

/ (Division)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1 /  num2

Description

The left number is divided by the right number. If either of the operands is a string, it is converted to a number.

Example

In Listing 7.28, the string “168” is converted to a number before being divided by the number 14. The result (12) of the division is stored in the variable x and displayed in the browser window.

Listing 7.28 Using the Division Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

//Initialize the variable aString with “168”.
aString = new String(“168”);

//Create the variable x and set it equal to the number 12.
x = aString / 14;

//Display the value stored in the variable x.
document.write("x = ",x);

// -->
</script>

/* / (Multi-line Comment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, IE 3+, Opera3+

 

Syntax

/* comments*/

Description

Every character that appears within the two comment tags is ignored by the JavaScript interpreter. Placing the tags on different lines allows comments to span multiple lines. Be careful not to nest comment tags within comment tags because this will lead to errors.

Example

Listing 7.29 demonstrates the use of multiple-line comments in JavaScript code.

Listing 7.29 Using the Multi-Line Comments


<script type=“text/javascript” language=“JavaScript”>
<!-- 

document.write("<h2>Multi-line Comments</h2>");

/* Even though this sentences spans multiple lines it is treated
as a comment because it begins and ends with comment tags.
document.write("Not displayed!");
Notice that even the JavaScript statement above is treated as a comment*/

// -->
</script>

// (Comment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, IE 3+, Opera3+

 

Syntax

// comment

Description

Every character that appears after this tag and on the same line as the tag is ignored by the JavaScript interpreter.

Example

Listing 7.30 demonstrates the use of the single line comment in JavaScript code.

Listing 7.30 Using Single Line Comments


<script type=“text/javascript” language=“JavaScript”>
<!-- 

document.write("<h2>Single Line Comments</h2>");

//Everything on the following line is considered a comment.
//document.write("Not Displayed!");

// -->
</script>

/= (Division Assignment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

variable /=  value

Description

The number stored in the variable on the left of the operator is divided by the number on the right. The result of the division overwrites the value in the variable on the left of the operator. If either of the operands is a string, it is converted to a number.

Example

In Listing 7.31, the string “8” is converted to a number before being used to divide by the number 32. The result of the division, which is 4, is stored in the variable x.

Listing 7.31 Using the Division and Assignment Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Initialize the variables x and aString.
x = 32;
aString = new String(“8”);

//The variable x is now equal to the number 4.
x /= aString;

//Display the value stored in the variable x.
document.write("x = ",x);

// -->
</script>

?: (Conditional)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

expression ? v value1 :  value2

Description

An expression that evaluates to a Boolean is always placed to the left of the question mark (?). If the expression evaluates to true,value1 is returned from the operation. If the expression evaluates to false,value2 is returned.

The same functionality of the conditional operator can be achieved with an if…else statement.

Example

In Listing 7.32, the conditional operator is shown along with a similar standard if statement. Both the conditional operator and the if statement have the same result, except that the conditional operator takes up less space. The string “The hamburgers are done!” are displayed for both operators.

Listing 7.32 The Conditional Operator and if Statement Are Compared


<script type=“text/javascript” language=“JavaScript”>
<!-- 

// Set the cooking status flag to “YES”.
doneCooking = “YES”

//Create 2 empty variables.
var message1;
var message2;

//Standard if statement
if (doneCooking == “YES”)
    message1 = "The hamburgers are done!";
else
    message1 = "The hamburgers are still cooking.";

//Same statement using conditional operator
message2 = (doneCooking == “YES”) ?
    "The hamburgers are done!" :
    "The  hamburgers are still cooking.";

// Print the message to the screen.  Notice both messages are the same!
document.write("The if statement returns: ",message1,"<br>");
document.write("The conditional operator returns: ",message2);

// -->
</script>

ˆ (Bitwise Exclusive OR)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1 ˆ  num2

Description

The bitwise exclusive OR (XOR) operator looks at the integer numbers on both sides of the operator as 32-bit binary numbers. The bitwise exclusive OR uses a special version of the logical OR operator, called exclusive OR, to evaluate each individual bit of a binary number.

Each of the 32 bits representing the number on the left of the operator is compared to the corresponding bit of the number on the right of the operator using the exclusive OR truth table shown in Table 7.3. The 32-bit binary result of the operation is converted to an integer value and returned.

Table 7.3 Bitwise Exclusive OR Truth Table

Image

Example

The code in Listing 7.33 uses the bitwise exclusive OR operator on the numbers 6 and3. The result of executing the code is the number 5, which is written to the browser window.

Listing 7.33 Using the Bitwise Exclusive OR Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

// integer = 32-bit binary representation
// 6 = 00000000000000000000000000000110
// 3 = 00000000000000000000000000000011
// 5 = 00000000000000000000000000000101

//Display the number 5 in the browser.
document.write("6 ˆ 3 = ", (6 ˆ 3) );

// -->
</script>

ˆ= (Bitwise Exclusive OR Assignment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

variable ˆ=  value

Description

The bitwise exclusive OR assignment operator (ˆ=) looks at the integer numbers on both sides of the operator as 32-bit binary numbers. The bitwise exclusive OR assignment operator uses a special version of the logical OR operator, called exclusive OR, to evaluate each individual bit of a binary number.

Each of the 32 bits representing the number on the left of the operator is compared to the corresponding bit of the number on the right of the operator using the exclusive OR truth table shown in Table 7.4. The 32-bit binary result of the operation is converted to an integer value and stored in the variable to the left of the operator.

Table 7.4 Exclusive OR Truth Table

Image

Example

Listing 7.34 uses the bitwise exclusive OR assignment operator on the numbers 10 and 6 to generate the result 12.

Listing 7.34 Using the Bitwise Exclusive OR Assignment Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

// integer = 32-bit binary representation
// 10 = 00000000000000000000000000001010
//  6 = 00000000000000000000000000000110
// 12 = 00000000000000000000000000001100

//Initialize the variable x with the number 10.
x = 10;

//The variable x is now equal to 12.
x ˆ= 6;

//Display the value stored in the variable x.
document.write("x = ",x);

// -->
</script>

| (Bitwise OR)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1 |  num2

Description

The bitwise OR operator looks at the integer numbers on both sides of the operator as 32-bit binary numbers. The truth table of the logical OR (||) operator, shown in Table7.5, is used to individually evaluate each of the 32 bits representing the number on the left of the operator to the corresponding bit of the number on the right of the operator. The 32-bit binary result of the bitwise OR operation is converted to an integer value and returned from the operation.

Table 7.5 Logical OR Truth Table

Image

Example

The code in Listing 7.35 uses the bitwise OR operator on the numbers 9 and 5. Executing the code displays the number 13 in the browser window.

Listing 7.35 Using the Bitwise OR Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

// integer = 32-bit binary representation
//  9 = 00000000000000000000000000001001
//  5 = 00000000000000000000000000000101
// 13 = 00000000000000000000000000001101

Display the number 13 in the browser window.
document.write("9 | 5 = ", (9 | 5) );

// -->
</script>

|| (Logical OR)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

expression1  ||  expression2

Description

The logical OR operator returns true if the left operand, right operand, or both operands evaluates to true. If both the operands evaluate to false, the result of the operation is false.

The implementation of the logical OR operator in JavaScript and JScript is more complex than what was just mentioned. The OR operation begins by evaluating the left operand. If the left operand evaluates to true, the basic logic of the OR operator is complete, so the right operand is never evaluated. But if the left operand evaluates to false, the right operand must be evaluated to determine the final result of the OR operation. In either case, the final result returned by the OR operation is actually the result of the last operand to be evaluated.

Example

Listing 7.36 demonstrates the complications associated with the logical OR operator. The first expression evaluates to true, causing the logical OR operation to evaluate to true. Because the first expression evaluates to true, the second expression, which assigns the number 7 to the variable x, is not evaluated so x remains equal to 8.

Listing 7.36 The Complicated Logical OR Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Initialize the variable x with the number 8.
x = 8;

//The assignment of 7 to the variable x never occurs
//since the first expression (8==x) evaluates to true.
if((8==x) || (x=7))
{
    document.write("The || evaluated TRUE!<br>");
}
else
{
    document.write("The || evaluated FALSE!<br>");
}

// x is equal to 8.
document.write("x=",x,"<br>");

// -->
</script>

|= (Bitwise OR Assignment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

variable  |=  value

Description

The bitwise OR assignment operator looks at the integer numbers on both sides of the operator as 32-bit binary numbers. The logical OR (||) operator individually evaluates each of the 32 bits representing the number on the left of the operator to the corresponding bit of the number on the right of the operator. The 32-bit binary result of the logical OR operation is converted to an integer value and stored in the variable on the left of the operator.

Example

Listing 7.37 uses the bitwise OR assignment operator on the numbers 2 and 5 to generate the number 7.

Listing 7.37 Using the Bitwise OR and Assignment Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

// integer = 32-bit binary representation
// 2 = 00000000000000000000000000000011
// 5 = 00000000000000000000000000000101
// 7 = 00000000000000000000000000000111

//Initialize the variable x with the number 2.
x = 2;

//Perform the bitwise OR assignment operation.
x |= 5;

//Display the value stored in the variable x.
document.write("x = ",x);

// -->
</script>

~ (Bitwise NOT)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

~operand

Description

The bitwise NOT operator begins by looking at the number to the right of the operator as a 32-bit binary number. Each bit of the given number is reversed so that all ones become zeros and all zeros become ones. The 32-bit binary result is converted to an integer value and returned from the bitwise NOT operation.

The result of inverting a number can be very confusing because of the way signed numbers are represented. Just remember that applying the bitwise NOT operator to a positive number will return the original number with the sign changed, minus one.

Example

The code in Listing 7.38 demonstrates the use of the bitwise NOT operator. Notice that the result of the operation is -3, which is the original number (2) with the sign reversed (-2) minus 1.

Listing 7.38 The Complicated Bitwise NOT Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

// integer = 32-bit binary representation
//  2 = 00000000000000000000000000000010
// -3 = 11111111111111111111111111111101


//Display the result of the Bitwise NOT Operator.
document.write("~2 = ",(~2));   //Displays -3

// -->
</script>

+ (Addition)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

operand1 +  operand2

Description

The addition operator provides two types of functionality depending on the data type of the operands. The first type of functionality is simple addition, in which the value on the left of the addition operator is added to the value on the right. For this type of addition, both operands must be numbers.

The second type of functionality provided by the addition operator is string concatenation. If either of the operands is a string, string concatenation is performed by first converting any non-string operand to a string. String concatenation is then performed by appending the string to the right of the operator to the end of the string located to the left of the operator.

Example

Listing 7.39 demonstrates the addition of numbers as well as string concatenation. Compare the Listing 7.39 to the result of executing the code as seen in Figure 7.2 to understand how addition is handled with various variable types.

Listing 7.39 Addition of Numbers and String Concatenation


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Initialize the variable aString.
aString = new String(“67”);

//answerNum contains the number 90.
answerNum = 67 + 23;

//answerStr contains the string “6723”.
answerStr = aString + 23;

//Print the result to the screen.
document.write("answerNum =",answerNum,"<br>");  //Displays 90
document.write("answerStr     =",answerStr);                      //Displays 6723

// -->
</script>

Figure 7.2 Using the addition operator to add numbers and concatenate strings.

Image

++ (Increment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

++variable       (Pre-Increment)
variable++        (Post-Increment)

Description

The pre-increment operator increments variable by 1. The new incremented value is returned by the operation.

The post-increment operator is similar to the pre-increment operator in that it increments variable by 1. However, the original value is returned by the operation before being incremented.

In both cases, if the operand is a string, it is converted to a number before performing the operation.

Example

Listing 7.40 demonstrates how the pre-increment and post-increment operators work. Notice that the variable num holds a string that is converted before performing the increment operation. The result of executing this code is shown in Figure 7.3.

Listing 7.40 Using the Increment Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

/* Store value in variable before pre-increment */
document.write("<h3>Before Pre-increment</h3>");
num = new String(“807”);   //num holds the string 807
document.write("num=",num,"<br>");    //807 is displayed.

/* Pre-increment the value stored in num */
returnValue = ++num;
document.write("<h3>After Pre-increment</h3>");
document.write("num=",num,"<br>");    //808 is displayed.
//808 is displayed by returnValue.
document.write("Value returned from operation is ",returnValue,"<br>");

/* Post-increment the value stored in num */
returnValue = num++;
document.write("<h3>After Post-increment</h3>");
document.write("num=",num,"<br>");    //809 is displayed.

//808 is displayed by returnValue.
document.write("Value returned from operation is ",returnValue,"<br>");

// -->
</script>

Figure 7.3 The difference between pre-increment and post-increment.

Image

+= (Addition Assignment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

variable +=  value

Description

The addition assignment operator provides two types of functionality depending on the data type of the operands. The first type of functionality is simple addition in which the value stored in the variable on the right of the addition assignment operator is added to the value on the left. The result of the addition overwrites the value stored in the variable on the left of the operator. If either of the operands is not a number or string, it will be converted to a number.

The second type of functionality provided by the addition assignment operator is string concatenation. If either of the operands is a string, string concatenation is performed by first converting any non-string operand to a string. String concatenation is then performed by appending the string to the right of the operator to the end of the string located to the left of the operator. The new string is stored in the variable on the left of the operator.

Example

In Listing 7.41, the addition assignment operator is used to add two numbers together as well as concatenate two strings.

Listing 7.41 Using the Addition and Assignment Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Initialize the variables num and str.
num = 42;
str = new String(“42”);

//Use the addition/assignment operator.
num += 8;    //num contains the number 50.
str += 8;    //str contains the string “428”.

//Display the results of the addition/assignment operator.
document.write("num = ",num,"<br>str = ",str);

// -->
</script>

< (Less Than)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1  <  num2

Description

The less than operator compares the value on the left of the operator to the value on the right. If the value on the left is less than the value on the right, true is returned from the operation. If the value on the left of the operator is greater than or equal to the value on the right, false is returned. If either of the operands is not a number or string, it will be converted to a number before performing the comparison.

Example

In Listing 7.42, the string “45” is converted to a number before performing the comparison. Because the number 45 is less than the number 68, the phrase "45 is less than 68" is returned.

Listing 7.42 Using the Less Than Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Initialize the variable str with “45”.
str = new String(“45”);

//Compare the variable to the number 68.
if(str < 68)
    document.write("45 is less than 68");
else
    document.write("Returned FALSE!");

// -->
</script>

<< (Shift Left)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1 <<  num2

Description

The shift left operator looks at the integer on the left of the operator as a 32-bit binary number. The number of positions specified by num2 shifts all the bits of num1 to the left. As the bits are shifted to the left, zeros are filled in on the right. Because the number can only be 32-bits long, the extra bits on the left are lost. The 32-bit binary result of the shifting operation is converted to an integer value and returned from the shift left operation.

Example

Listing 7.43 shifts the bits that make up the number 2 to the left two positions, which results in the number 8.

Listing 7.43 Using the Shift Left Operator

<script type=“text/javascript” language=“JavaScript”>
<!-- 

// integer = 32-bit binary representation
// 2 = 00000000000000000000000000000010
// 8 = 00000000000000000000000000001000

//Assign the number 8 to the variable x.
x = 2 << 2;

//Display the value stored in the variable x.
document.write("2 << 2 = ",x);

// -->
</script>

<<= (Shift Left Assignment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

variable <<=  num

Description

The shift left assignment operator looks at the integer stored in the variable to the left of the operator as a 32-bit binary number. All the bits in this number are shifted to the left by the number of positions specified by the integer to the right of the operator. As the bits are shifted to the left, zeros are filled in on the right. Because the number can only be 32-bits long, the extra bits on the left are lost. The 32-bit binary result of shifting operation is converted to an integer value and stored in the variable to the left of the operator.

Example

In Listing 7.44, the 32-bit binary version of the number 3, which is stored in the variable x, is shifted two positions to the left. The result of this operation, the number 12, is stored in the variable x.

Listing 7.44 Using the Shift Left Assignment Operator

<script type=“text/javascript” language=“JavaScript”>
<!-- 

// integer = 32-bit binary representation
//  3 = 00000000000000000000000000000011
// 12 = 00000000000000000000000000001100

//Initialize the variable x with the number 3.
x = 3;

//The variable x is now equal to the number 12.
x <<= 2;

//Display the value stored in the variable x.
document.write("x = ",x);

// -->
</script>

<= (Less Than or Equal)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1 <=  num2

Description

The less than or equal operator compares the number on the left of the operator to the number on the right. If the number on the left is less than or equal to the number on the right, true is returned from the operation. If the number on the left of the operator is greater than the number on the right, false is returned.

Example

In Listing 7.45, the string “34” would be converted to a number before performing the comparison. Because the number 34 is less than the number 77, the phrase "34 is less than or equal to 77" would be returned.

Listing 7.45 Using the Less Than or Equal Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Initialize the variable str to “34”.
str = new String(“34”);

//Compare the value stored in the variable to the number 77.
if(str <= 77)
    document.write("34 is less than or equal to 77");
else
    document.write("Returned FALSE!");

// -->
</script>

= (Assignment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

variable =  value

Description

The value to the right of the operator is stored in the variable to the left of the operator.

Example

In Listing 7.46, the assignment operator is used to assign various types of values to variables. The type of operator is then used to determine the type value stored in the variables. The types are then displayed in the browser (x is a number,y is a string, and z is a boolean).

Listing 7.46 Using the Assignment Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Number
x = 456;                   //x contains a number.
document.write("x is a ",typeof x,"<br>");

//String
y = new String(“Hello”)    //y contains a String.
document.write("y is a ",typeof y,"<br>");

//Boolean
z = true;                 //z contains a Boolean.
document.write("z is a ",typeof z);

// -->
</script>

-= (Subtraction Assignment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

variable -= value

Description

The number to the right of the operator is subtracted from the number stored in the variable to the left of the operator. The result of the operation overwrites the value stored in the variable to the left of the operator. If either operand is a string, an attempt is made to convert the string to a number before performing the subtraction.

Example

In Listing 7.47, the string “878” is converted to a number before the subtraction operation begins. The number 55 is subtracted from 878 and the result, 823, is stored in the variable answer.

Listing 7.47 Using the Subtraction Assignment Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Initialize the variable aString with “878”.
aString = new String(“878”);

//Assign the number 823 to the variable answer.
answer -= 55;

//Display the values stored in the variable answer.
document.write("answer = ",answer);

// -->
</script>

== (Equal)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

expression1 ==  expression2

Description

The equal operator compares the value on the left of the operator to the value on the right of the operator. If the values are equal, true is returned from the operation. If the values are not equal, false is returned from the operation.

JavaScript attempts to convert the operands to the same data type before comparing the values for all versions of JavaScript except 1.2. JavaScript adheres to the following rules when performing type conversion:

True is converted to the number 1, and false is converted to 0 before being compared.

• If either of the operands is NaN, the equality operator returns false.

• Null and undefined are equal.

• Null and undefined are not equal to 0 (zero), "" (empty string), or false.

• If a string and a number are compared, attempts to convert the string to a number and then checks for equality.

• If an object and a string are compared, attempts to convert the object to a string and then checks for equality.

• If an object and a number are compared, attempts to convert the object to a number and then checks for equality.

• If both operands of an equality operation are objects, the address of the two objects are checked for equality.

Example

In Listing 7.48, the string “749” is converted to a number (except in JavaScript 1.2, in which type conversion is not performed) so that two numbers are compared. Because the left operand is equal to the right operand, the phrase "The string 749 is EQUAL to the number 749" is written to the browser window.

Listing 7.48 Using the Equal Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//The string is converted to a number before performing the comparison.
if(“749” == 749)
{
    document.write("The string 749 is EQUAL to the number 749");
}
else
{
    document.write("The string 749 is NOT equal to the number 749");
}

// -->
</script>

=== (Identity)

JavaScript 1.3+, ECMAScript 3E+, JScript 1.0+

Nav4.06+, IE 3+, Opera5+

 

Syntax

expression1 ===  expression2

Description

The identity operator compares the first operand to the second operand. If the value on the left is equal to the value on the right side of the operator, true is returned from operation. If the values are not equal, false is returned.

Example

In Listing 7.49, the string “326” is NOT converted to a number, so the two operands are not the same type. Because the two operands are not the same type, they are not equal, so the phrase "The string 326 is NOT equal to the number 326" is written to the browser window.

Listing 7.49 Using the Identity Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//A string is compared to a number.
if(“326” === 326)
{
    document.write("The string 326 is NOT equal to the number 326");
}
else
{
    document.write("The string 326 is EQUAL to the number 326");
}
// -->
</script>

> (Greater Than)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1 >  num2

Description

The greater than operator compares the value on the left of the operator to the value on the right. If the value on the left is greater than the value on the right, true is returned from the operation. If the value on the left of the operator is less than or equal to the value on the right, false is returned. If either of the operands is not a number, it is converted to a number before performing the comparison.

Example

In Listing 7.50, the string “112” would be converted to a number before performing the comparison. Because the number 112 is greater than the number 68, the phrase "112 is greater than 68" is returned.

Listing 7.50 Using the Greater Than Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Initialize the variable str with the string “112”.
str = new String(“112”);

//Compare the value in the variable to a number.
if(str > 68)
    document.write("112 is greater than 68");
else
    document.write("Returned FALSE!");

// -->
</script> >

>= (Greater Than or Equal)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+ IE 3+, Opera3+

Syntax

variable >=  value

Description

The greater than or equal operator compares the number on the left of the operator to the number on the right. If the number on the left is greater than or equal to the number on the right, true is returned from the operation. If the number on the left of the operator is less than the number on the right, false is returned.

Example

In Listing 7.51, the string “95” would be converted to a number before performing the comparison. Because the number 95 is greater than the number 44, the phrase "95 is greater than or equal to 44" is returned.

Listing 7.51 Using the Greater Than Or Equal Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Initialize the variable str.
str = new String(“95”);

//Compare the value stored in the variable to the number 44.
if(str >= 44)
    document.write("95 is greater than or equal to 44");
else
    document.write("Returned FALSE!");

// -->
</script>

>> (Shift Right with Sign)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1 >>  num2

Description

The shift right with sign operator looks at the integer to the left of the operator,num1, as a 32-bit binary number. All the bits in this number are shifted to the right by the number of positions specified by num2. As the bits are shifted to the right, either ones or zeros are filled in on the left. If the original number is positive, zeros are added to the left side of the binary number. On the other hand, if the original number is negative, ones are used. Because the result can only be 32-bits long, the extra bits on the right are lost. The 32-bit binary result of shifting operation is converted to an integer value and returned from the shift right with sign operation.

Example

Listing 7.52 shifts the bits that make up the number 14 to the right two positions, which results in the number 3. The code also shifts the bits that make up the number -14 to the right one position, which results in the number -2.

Listing 7.52 Using the Shift Right with Sign Operator


<script type=“text/javascript” language=“JavaScript”>
<!--

// integer = 32-bit binary representation
// 14 = 00000000000000000000000000001110
//  3 = 00000000000000000000000000000011

//The number 3 is assigned to the variable x.
x = 14 >> 2;

//Display the value stored in the variable.
document.write("14 >> 2 = ",x);

//--------------------------------------
document.write("<br>");

// integer = 32-bit binary representation
// -4 = 11111111111111111111111111111100
// -2 = 11111111111111111111111111111110

//The number -2 is stored in the variable y.
y = -4 >> 1;    //y is equal to -2.

//Display the value stored in the variable y.
document.write("-4 >> 1 = ",y);

// -->
</script>

>>= (Shift Right with Sign Assignment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

variable  >>= v value

Description

The shift right with sign assignment operator (>>=) looks at the integer to the left of the operator as a 32-bit binary number. All the bits in this number are shifted to the right by the number of positions specified by the integer to the right of the operator. As the bits are shifted to the right, either ones or zeros are filled in on the left. If the original number is positive, zeros are added to the left side of the binary number. On the other hand, if the original number is negative, ones are used. Because the result can only be 32-bits long, the extra bits on the right are lost. The 32-bit binary result of shifting operation is converted to an integer value and stored in the variable to the left of the operator.

Example

In Listing 7.53, the 32-bit binary version of the number 15, which is stored in the variable x, is shifted one position to the right. The result of this operation, the number 7, is stored in the variable x.

Listing 7.53 Using the Shift Right with Sign Assignment Operator


<script  type=“text/javascript” language=“JavaScript”>
<!-- 

// integer = 32-bit binary representation
// 15 = 00000000000000000000000000001111
//  7 = 00000000000000000000000000000111

//Initialize the variable x with the number 15.
x = 15;

//The variable x is now equal to 7.
x >>= 1;

//Display the values stored in the variable x.
document.write("x = ",x);

// -->
</script>

>>> (Shift Right Zero Fill)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

num1 >>>  num2

Description

The shift right zero fill operator looks at the integer to the left of the operator as a 32-bit binary number. All the bits in this number are shifted to the right by the number of positions specified by the integer to the right of the operator. As the bits are shifted to the right, zeros are filled in on the left, regardless of the sign of the original integer. Because the result can only be 32-bits long, the extra bits on the right are lost. The 32-bit binary result of this shifting operation is converted to an integer value and returned from the shift right zero fill operation.

Example

Listing 7.54 shifts the bits that make up the number 13 to the right one position, which results in the number 6. The number 1073741822 results from shifting the bits that make up the number –8 two positions to the right.

Listing 7.54 Using the Shift Right Zero Fill Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

// integer = 32-bit binary representation
// 13 = 00000000000000000000000000001101
//  6 = 00000000000000000000000000000110

//Assign the number 6 to the variable x.
x = 13 >>> 1;

//Display the value stored in the variable x.
document.write("13 >>> 1 = ",x);

//--------------------------------------
document.write("<br>");

// integer = 32-bit binary representation
//         -8 = 11111111111111111111111111111000
// 1073741822 = 00111111111111111111111111111110

//Assign the number 1073741822 to the variable y.
y = -8 >>> 2;

//Display the value stored in the variable y.
document.write("-8 >>> 2 = ",y);

// -->
</script>

>>>= (Shift Right Zero Fill Assignment)

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+

 

Syntax

variable >>>=  value

Description

The shift right zero fill assignment operator (>>>=) looks at the integer to the left of the operator as a 32-bit binary number. All the bits in this number are shifted to the right by the number of positions specified by the integer to the right of the operator. As the bits are shifted to the right, zeros are filled in on the left, regardless of the sign of the original integer. Because the result can only be 32-bits long, the extra bits on the right are lost. The 32-bit binary result of this shifting operation is converted to an integer value and stored in the variable to the left of the operator.

Example

In Listing 7.55, the 32-bit binary version of the number –6, which is stored in the variable x, is shifted one position to the right. The result of this operation, the number 1073741822, is stored in the variable x.

Listing 7.55 Using the Shift Right Zero Fill Assignment Operator


<script type=“text/javascript” language=“JavaScript”>
<!-- 

// integer    =   32-bit binary representation
//                   -6 = 11111111111111111111111111111010
// 1073741822 = 00111111111111111111111111111110
//Initialize the variable x with the number -6.
x = -6;

//The variable x now contains the number 1073741822.
x >>>= 2;

//Display the value stored in the variable x.
document.write("x = ",x);

// -->
</script>

abstract

JavaScript 1.2+, ECMAScript 2E+, JScript 5+

Nav4+, NES 3+, IE5+, Opera5+

 

Syntax

ReservedKeyword

Description

The abstract keyword has not been implemented in JavaScript to date, but has been reserved for future use.

Example

This keyword has not been implemented, therefore no example is provided.

ActiveXObject

JScript3.0+

IE4+

 

Syntax

var variable  = new ActiveXObject(serverName.typeName,location)

Description

The ActiveXObject creates a reference to an object that is connected to another application or programming tool through automation interfaces. The arguments used by this object are listed in Table 7.6.

Table 7.6 Arguments Associated with ActiveXObject

Image

Example

Listing 7.56 uses the ActiveXObject to create a multiplication table in a Microsoft Excel document. Excel will be started automatically.

Listing 7.56 Create a Multiplication Table in an Excel Document


<script type="text/jscript" language=“JScript”>
<!-- 

var ExcelSheet = new ActiveXObject("Excel.Sheet");

// Make Excel visible through the Application object.
ExcelSheet.Application.Visible = true;

//Create multiplication table in Excel.
for(i=1;i<11;i++)
{
    // numbers to be multiplied in first two rows.
    ExcelSheet.ActiveSheet.Cells(i,1).Value = i;
    ExcelSheet.ActiveSheet.Cells(i,2).Value = 9;

    // Create Excel string to handle multiplication.
    var aString = new String("=A");
    aString += i;
    aString += "*B";
    aString += i;
    ExcelSheet.ActiveSheet.Cells(i,3).Value = aString;
}

// -->
</script>

Arguments

JavaScript 1.1+, ECMAScript 1E+, JScript 1.0+

Nav3+, IE3+, Opera5+

 

Syntax

arguments
arguments [index]

Description

The Arguments object is an array that contains all the arguments passed into the currently executing function as well as a few other useful properties. This object is automatically created and initialized when a function is invoked and goes out of scope as soon as the code function finishes executing. To access arguments passed into a function, simply use array brackets to specify an index. Table 7.7 lists the properties associated with the Argument object.

Table 7.7 Properties Associated with the Arguments Object

Image

Example

In Listing 7.57, a function is created to display an individual’s favorite food in an alert box. The function is called when the buttons are pressed. The arguments passed to this function are accessed within the function with the Arguments object array brackets.

Listing 7.57 Using the Arguments Object to Display People’s Favorite Foods


<html>
<body>
Select a person’s name to discover their favorite food!

<form>
<input type=“button”
            value=“Meredith”
            OnClick=displayFood(this,“pizza”)>
<input type=“button”
            value=“Allison”
            OnClick=displayFood(this,“beans”)>
<input type=“button”
            value=“BayLeigh”
            OnClick=displayFood(this,“carrots”)>
<input type=“button”
            value=“Michael”
            OnClick=displayFood(this,“corn”)>
<input type=“button”
            value=“Rob”
            OnClick=displayFood(this,“hotdogs”)>
</form>

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a function that displays a person’s favorite food.
function displayFood()
{
    //Create a string that contains the name of the person.
    var aString = arguments[0].value;
    aString += "'s favorite food is ";

    //Add the favorite food to the end of the string.
    aString += arguments[1];

    //Display the string in an alert box.
    alert(aString);
}

// -->
</script>

</body>
</html>

Arguments.callee

JavaScript 1.2+, ECMAScript 1E+, JScript 5.5+

Nav4+, IE5.5+, Opera5+

 

Syntax

arguments.callee

Description

The callee property of the Arguments object contains the function that is currently executing. This is useful if the function has no name.

Example

In Listing 7.58, a function is created to display an individual’s favorite food in an alert box. The function is called when the buttons are clicked. The code that makes up the executing function is displayed using the callee property.

Listing 7.58 Using the callee Property of the Arguments Object


<html>
Learn what functions are used when you press the buttons
below that represent a person’s favorite food!

<form>
<input type=“button”
           value=“Meredith”
           OnClick=displayFood(this,“pizza”)>
<input type=“button”
           value=“Allison”
           OnClick=displayFood(this,“beans”)>
<input type=“button”
           value=“BayLeigh”
           OnClick=displayFood(this,“carrots”)>
<input type=“button”
           value=“Michael”
           OnClick=displayFood(this,“corn”)>
<input type=“button”
           value=“Rob”
           OnClick=displayFood(this,“hotdogs”)>
</form>

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a function that displays a person’s favorite food.
function displayFood()
{
    //Create a string that contains the name of the person.
    var aString = arguments[0].value;
    aString += "'s favorite food is ";

    //Add the favorite food to the end of the string.
    aString += arguments[1];

    //Display the string in an alert box.
    alert(aString);

    //Display the function using the callee property.
    alert(arguments.callee.toString());
}

// -->
</script>
</html>

Arguments.caller

JavaScript 1.2+

Nav4+

 

Syntax

arguments.caller

Description

The caller property of the Arguments object contains the Arguments object of the calling function. If the given function was not executed from within another function, null is stored in this property.

Example

Listing 7.59 creates two functions. One displays an individual’s favorite food in an alert box, whereas the other displays the number of arguments associated with the calling function. Anytime a button is clicked, an alert box displays the favorite food. This function then calls the second function to display an alert box saying two arguments were passed into the first function.

Listing 7.59 Using the caller Property of the Arguments Object


<html>
Select a person’s name to discover their favorite food!

<form>
<input type=“button”
           value=“Meredith”
           OnClick=displayFood(this,“pizza”)>
<input type=“button”
           value=“Allison”
           OnClick=displayFood(this,“beans”)>
<input type=“button”
           value=“BayLeigh”
           OnClick=displayFood(this,“carrots”)>
<input type=“button”
           value=“Michael”
           OnClick=displayFood(this,“corn”)>
<input type=“button”
           value=“Rob”
           OnClick=displayFood(this,“hotdogs”)>
</form>

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Display the number of arguments in the function that calls this function.
function displayArgLength()
{
    var argLengthStr = "The calling function contained ";
    argLengthStr += arguments.caller.length;
    argLengthStr += " arguments.";
    alert(argLengthStr);
}

//Create a function that displays a person’s favorite food.
  function displayFood()
{
    //Create a string that contains the name of the person.
    var aString = arguments[0].value;
    aString += "'s favorite food is ";

    //Add the favorite food to the end of the string.
    aString += arguments[1];

    //Display the string in an alert box.
    alert(aString);

    displayArgLength();
}

// -->
</script>
</html>

Arguments.length

JavaScript 1.1+, ECMAScript 1E+, JScript 5.5+

Nav3+, IE5.5+, Opera5+

 

Syntax

arguments.length

Description

The length property of the Arguments object contains the number of arguments that were passed into the function to which the Arguments object is associated. If fewer arguments are passed in than are specified in the definition of the function, the length property will only contain the number of arguments passed into the function. This number matches the number of elements in the arguments array associated with the Arguments object.

Example

In Listing 7.60, the length property of the Arguments object is used to process any number of arguments passed into the displayFood() function.

Listing 7.60 Using the length Property to Access Elements of the Arguments Object


<html>
Select a person’s name to discover their favorite foods!

<form>
<input type=“button”
           value=“Meredith”
           OnClick=displayFood(this,“pizza”,“salad”,“cake”)>
<input type=“button”
           value=“Allison”
           OnClick=displayFood(this,“beans”,“potatoes”)>
<input type=“button”
           value=“BayLeigh”
           OnClick=displayFood(this,“carrots”)>
<input type=“button”
           value=“Michael”
           OnClick=displayFood(this,“corn”,“beans”)>
<input type=“button”
           value=“Rob”
           OnClick=displayFood(this,“hotdogs”)>
</form>

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a function that displays a person’s favorite foods.
function displayFood()
{
    //Create a string that contains the name of the person.
    var aString = arguments[0].value;
    aString += "'s favorite foods are: ";

    //Add all the favorite foods to the end of the string.
    for(var i=1; i<arguments.length; i++)
    {
       aString += arguments[i];
       aString += ", ";
    }

    //Display the string in an alert box.
    alert(aString);
}

// -->
</script>

Array

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES3+, IE 4+, Opera3+

 

Syntax

var variable  = new Array()
var variable  = new Array(int)
var variable  = new Array(arg1, …, argN)

Description

Although arrays can be created with the basic JavaScript object, the Array object provides a much easier way to create and manage arrays.

Table 7.8 lists the argument and return values associated with this object’s constructors. These constructors create a new array and, in two cases, initialize the Array object based on the arguments passed in the parameter list. The constructor that has no arguments sets the length property to 0.

Table 7.8 Arguments and Return Values Associated with the Array Object

Image

Table 7.9 lists the properties and methods used by the Array object.

Table 7.9 Properties and Methods Used by the Array Object

Image

Example

Listing 7.61 creates an array of numbers using the Array constructor. Once created, the elements are displayed on the screen using bracket notation ([]).

Listing 7.61 Creating an Array and Accessing Its Elements


<html>

<h2>Creating and Accessing Arrays</h2>

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a new array that contains 3 numbers.
numArray = new Array(45,67,34);
document.write("Created an array of numbers that contains 45, 67, and 34<br>");

//Display the contents of the array.
document.write("[0]=",numArray[0],"<br>"); // will display 45
document.write("[1]=",numArray[1],"<br>"); // will display 67
document.write("[2]=",numArray[2]);            // will display 34

// -->
</script>

</html>

Array.concat( )

JavaScript 1.2+, ECMAScript 3E+, JScript 3.0+

Nav4+, NES3+, IE 4+, Opera5+

 

Syntax

array.concat(arg1,…argN)

Description

The concat() method adds the elements listed in the parameter list to the end of the existing array and returns the result. The original is not changed by this method. Should any of the arguments be Array, the elements of that array are concatenated to the array that called the method.

Table 7.10 lists the argument and return values associated with this method.

Table 7.10 Arguments and Return Values Associated with concat()

Image

Example

Listing 7.62 uses the concat() method to display the total inventory of two grocery store shelves. Notice how the multidimensional arrays wereconcatenated together in Figure 7.4.

Listing 7.62 Using concat() to Display Inventory


<script type=“text/javascript” language=“JavaScript”>
<!--
//Display the elements in the array.
function displayElements(theArray)
{
    //Access each element in the array.
    for(i=0; i<theArray.length; i++)
    {
       //Display the element.
       document.write("  - ",theArray[i][1]," ");

       document.write(theArray[i][0],"<br>");
    }
}

//Create a grocery shelf using an array to represent
//the items on each shelf.
shelf1 = new Array([“apples”,10],[“oranges”,25]);
document.write("Shelf 1 contains:<br>");

//Display the items on shelf 1.
displayElements(shelf1);

//Create a second grocery shelf using an array to represent
//the items on each shelf.
shelf2 = new Array([“grapes”,50],[“bananas”,3],[“lemons”,8]);
document.write("Shelf 2 contains:<br>");

//Display the items on shelf 2.
displayElements(shelf2);

//Create a master inventory list by concatenating
//the two shelf arrays into one array.
inventory = shelf1.concat(shelf2);

//Display all the items on all the shelves.
document.write("<br>The total inventory contains:<br>");
displayElements(inventory);
// -->
</script>

Figure 7.4 Concatenate the items on two grocery store shelves.

Image

Array.constructor

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES3+, IE4+, ;Opera3+

 

Syntax

array.constructor

Description

The constructor property of the Array object is used to create the object’s prototype.

Example

Listing 7.63 demonstrates the constructor property as it relates to the Array object.

Listing 7.63 The Array’s constructor Property

<script type=“text/javascript” language=“JavaScript”>
<!--
// Create a new array object using the constructor property.
myArray = new Array(“Mike”,“Eric”,“Ory”,“Jason”,“Jonathon”,“Kevin”);
if(myArray.constructor == Array){
    document.write("Object was created");
}
// -->
</script>

Array.index

JavaScript 1.2+, JScript 3.0+ Nav4+, NES3+, IE 4+, Opera4+

 

Syntax

array.index

Description

The index property is a read-only property that contains the position of a regular expression match within a string. This property only appears in the Array object that is returned from the following regular expression related methods:

RegExp.exec()

String.match()

String.replace()

Example

Listing 7.64 creates a regular expression string that contains the search string “red”.The exec() method is used to find the regular expression within a string. The index property is then used to display "The word red was found at position 4", which contains the position character position (4) within the string where the word “red” was found.

Listing 7.64 Using the index Property to Display the Position of a Match

<script type=“text/javascript” language=“JavaScript”>
<!--
myReg=/red/;
myArray = myReg.exec("The red ball.");
document.write("The word ‘red’ was found at position ",myArray.index);
// -->
 </script>

Array.input

JavaScript 1.2+, JScript 3.0+

Nav4+, NES3+, IE 4+, Opera4+

 

Syntax

array.input

Description

The input property is a read-only property that contains the string against which the regular expression was matched. This property only appears in the Array object that is returned from the following regular expression related methods:

RegExp.exec()

String.match()

String.replace()

Example

Listing 7.65 creates a regular expression string that contains the search string “red”. The exec() method is used to find the regular expression within a string. The inputproperty is then used to display the string that was searched.

Listing 7.65 Using the index Property to Display the Regular Expression

<script type=“text/javascript” language=“JavaScript”>
<!--
myReg=/red/;
myArray = myReg.exec("The red ball.");
document.write("The word red was found at position ",myArray.index);
// -->
 </script>

Array.join()

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES3+, IE 4+, Opera3+

 

Syntax

array.join()
array.join(string)

Description

The join() method converts all the elements of the array to strings and then concatenates all the strings into one string. If an argument is provided in the parameter list, it is used to separate the elements in the string returned by the method. Table 7.11 lists the argument and return values associated with this method.

Table 7.11 Arguments and Return Values Associated with join()

Image

Example

Listing 7.66 creates an array of fruits. The contents of this array are displayed on the screen using the join() method. A dash is specified as the delimiter used to separate the array elements when they are written to the screen as a string.

Listing 7.66 Using the join() Method to Display the Elements of an Array

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create an array that contains 3 fruits.
fruit = new Array(“Apple”,“Orange”,“Grape”);

//List the contents of the fruit array as a string
//with a dash separating each item.
aString = fruit.join("-");  //aString = "Apple-Orange-Grape"

//Display the string generated from using the join() method.
document.write("The fruit array contains: ",aString);

// -->
</script>

Array.lastIndex

JavaScript 1.2+, JScript 3.0+

Nav4+, NES3+, IE 4+

 

Syntax

array.lastIndex

Description

The lastIndex property is a read-only property that contains the position following the last character in a regular expression match. This property only appears in the Array object that is returned from the following regular expression related methods:

RegExp.exec()

String.match()

String.replace()

Example

Listing 7.67 creates a regular expression string that contains the search string “red”. The exec() method is used to find the regular expression within a string. The lastIndex property is then used to display the number 7, which is the position following the word “red” that was found in the string.

Listing 7.67 Using the lastIndex Property to Display the Position Following the Match

<script type=“text/javascript” language=“JavaScript”>
<!--
myReg=/red/;
myArray = myReg.exec("The red ball.");
document.write("The lastIndex property is set to ",myArray.lastIndex);
// -->
 </script>

Array.length

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES3+, IE 4+, Opera3+

 

Syntax

array.length

Description

The length property holds the number of elements in the array. This property is a read/write variable. If the length property is overwritten with a number that is larger than the original number, new elements are added to the end of the array and assigned undefined values. If the length property is overwritten with a number that is smaller than the original number, elements at the end of the array are lost.

Example

Listing 7.68 creates an array of coins. The number of coins in the array is then reduced from 4 to 3 by modifying the length property so the array contains only three elements. Because the quarter was the last element in the array, it was removed when the length property was changed.

Listing 7.68 Using the length Property to Reduce the Number of Elements in an Array

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create an array of coins.
coins = new Array(“Penny”,“Nickel”,“Dime”,“Quarter”);

x = coins.length;  //x contains 4.
coins.length = 3   //“Quarter” was removed from array.

//Display the contents of the array.
document.write("The coins array contains: ", coins.join(','));

// -->
</script>

Array.pop()

JavaScript 1.2+, ECMAScript 3E+, JScript 5.5+

Nav4+, NES3+, IE5.5+, Opera5+

 

Syntax

array.pop()

Description

The pop()method “pops” elements off the end of the array by deleting the last element of the array and setting the array’s length property to one less than its current value. The element popped off the end of the array is returned from the method. Table 7.12 shows the return value associated with this method.

Table 7.12 Arguments and Return Values Associated with pop()

Image

Example

In Listing 7.69, an array of pages is created to represent a stack of papers. The pop() method removes and returns the top-most paper. After the pop() method is executed, the variable currentPaper contains “Page3”, and the array’s length property is 2.

Listing 7.69 Using the pop() Method to Remove Elements from the End of an Array

<script type=“text/javascript” language=“JavaScript”>
<!-- 
//Create an array of papers and remove the top page.
pileOfPapers = new Array(“Page1”,“Page2”,“Page3”);
currentPaper = pileOfPapers.pop();  //Removed Page3
document.write(currentPaper," was removed from the pile.");

// -->
</script>

Array.prototype

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES3+, IE 4+, Opera5+

 

Syntax

array.prototype.property

Array.prototype.method

Description

The prototype property allows you to add new properties and methods (designated as property/method in the Syntax section) to the Array object that can be used throughout your code.

Example

In Listing 7.70, the prototype property is used to provide a pop() method for working with arrays. Even though a pop() method is already available, a new pop() method will be created. This method overrides the functionality of the Array.pop() method. The new pop() method is used at the end of the code to remove an the “Peach” element from the array of juice flavors. The contents of the flavorArray are displayed before and after the new pop() method is executed to show that the “Peach” flavor was removed.

Listing 7.70 Assigning a New Method to the Array Object with the Prototype Property

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//This function removes the last element in the array.  This last
//element is returned from the function.
function pop()
{
    if(this.length != 0)
    {
       var lastElement = this[this.length-1];  //Get last element.
       this.length = this.length-1;            //Remove last element from array.
       return(lastElement);                    //Return the last element.

    }
}

//Make the pop() function available to all Array objects.
//This will override the pop() method provided by the Array object in Netscape.
Array.prototype.pop = pop;

//Create an Array of juice flavors.
var flavorArray = new Array(“Strawberry”,“Blueberry”,“Peach”);

//Display the contents of the flavor array.
document.write("The flavor array initially contains: ");
document.write(flavorArray.join(', '),"<br>");

//Remove Peach from the array.
var removedElement = flavorArray.pop();
document.write(removedElement," was removed from the flavor array.<br>");

//Display the contents of the flavor array after the pop() method.
document.write("The flavor array now contains: ");
document.write(flavorArray.join(', '),"<br>");

// -->
</script>

Array.push()

JavaScript 1.2+, ECMAScript 3E+, JScript 5.5+

Nav4+, NES3+, IE5.5+, Opera5+

 

Syntax

array.push (arg1,…argN)

Description

The push() method “pushes” the elements specified in the parameter list on to the end of the array in the order they were listed. Table 7.13 shows the arguments and return values associated with this method.

Table 7.13 Arguments and Return Values Associated with push()

Image

Example

In Listing 7.71, an array of pages is created to represent a stack of papers. The push() method puts two more pages on the end of the array. After the push() method is executed, the variable currentPaper contains “Page4”, and the array’s length property is 4.

Listing 7.71 Using the push() Method to Add Elements to the End of an Array

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create an array of papers.
pileOfPapers = new Array(“Page1”,“Page2”);

//Add 2 more pages to the end of the array.
currentPaper = pileOfPapers.push(“Page3”,“Page4”);

//Display the papers in the pile.
document.write(pileOfPapers.join(',')," are in the pile.");

// -->
</script>

Array.reverse()

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES3+, IE 4+, Opera5+

 

Syntax

array.reverse()

Description

The reverse() method reverses the order of the elements in the array according to the array index numbers.

Example

Listing 7.72 creates an array representing a line of people. The reverse() method is called to reverse the order of the names so that Polly is the first element, Leslie is the second element, and Cheryl is the last element.

Listing 7.72 Reversing Element Positions in an Array with the reverse() Method

<script type=“text/javascript” language=“JavaScript”>
<!-- 
//Create an array of names representing people in a grocery store line.
lineOfPeople = new Array(“Cheryl”,“Leslie”,“Polly”);
lineOfPeople.reverse();   //Reverse the items in the array.

//Display the names in the array. Notice the reversed ordering.
document.write("lineOfPeople[0]=",lineOfPeople[0],"<br>");
document.write("lineOfPeople[1]=",lineOfPeople[1],"<br>");
document.write("lineOfPeople[2]=",lineOfPeople[2],"<br>");

// -->
</script>

Array.shift()

JavaScript 1.2+, ECMAScript 3E+, JScript 5.5+

Nav4+, NES3+, IE5.5+, Opera5+

 

Syntax

array.shift()

Description

The shift() method deletes and returns the first element of the array. Once deleted, all the remaining elements are shifted down one spot, so the first position is filled by the element that was previously in the second position. Table 7.14 shows the return value associated with this method.

Table 7.14 Return Value Associated with shift()

Image

Example

Listing 7.73 creates an array representing people waiting for a table at a restaurant. The shift() method pulls the first name off the list and shifts all the other names down one position. After the shift() method is executed, the variable personToSeat now contains Kent. Jon is shifted to lineOfPeople[0] and Jeremy to lineOfPeople[1].

Listing 7.73 Removing the First Element from an Array with the shift() Method

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create an array representing a line of people at a restaurant.
lineOfPeople = new Array(“Kent”,“Jon”,“Jeremy”);
personToSeat = lineOfPeople.shift();  //Kent pulled from array
//Display name of person removed from array.
document.write("Please seat ",personToSeat,"<br>");

//Display people left in the array.
document.write("People waiting for a seat: ",lineOfPeople.join(', '));
// -->
</script>

Array.slice()

JavaScript 1.2+, ECMAScript 3E+, JScript 3.0+

Nav4+, NES3+, IE 4+, Opera5+

 

Syntax

array.slice(start)
array.slice(start, stop)

Description

The slice() method returns a new array that contains the elements of the original array starting at position start and ending at the element position before stop. If no stop position is specified, the new array will contain the elements of the original array, starting at the position stated in start through the end of the array. Table 7.15 lists the arguments and return values associated with this method.

Table 7.15 Arguments and Return Values Associated with slice()

Image

Example

In Listing 7.74, an array of numbers is created. A new array of numbers is derived from the original array of numbers using the slice() method. After the slice() method is executed, the array newNumArray contains the elements 23 and 759.

Listing 7.74 Selecting a Subsection from an Array with the slice() Method

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create an array of 4 numbers and display the contents.
numArray = new Array(345,23,759,5);
document.write("numArray contains the numbers: ",numArray.join(', '),"<br>");

//Create a new array from part of the original array.
newNumArray = numArray.slice(1,3);    // new array contains [23,759].

//Display the contents of the new array.
document.write("newNumArray contains the numbers: ",newNumArray.join(',
'),"<br>");

// -->
</script>

Array.sort()

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES3+, IE 4+, Opera5+

 

Syntax

array.sort()
array.sort (function)

Description

The sort()method rearranges the elements of the array based on a sorting order. Table7.16 lists the argument associated with this method. If the method has no parameters, JavaScript attempts to convert all the elements of the array to strings and then sort them alphabetically. If the array should be sorted some other way, a function must be provided to handle the new sorting algorithm.

Table 7.16 Argument Associated with sort()

Image

As mentioned before, if the array should be sorted some other way than jscriptbetically, a function must be provided to handle the new sorting algorithm. The function specified must operate based on the following rules:

• The function must accept two arguments that are to be compared.

• The function must return a number indicating the order of the two arguments in relation to each other.

• If the first argument should appear before the second argument, a number less than zero should be returned from the function.

• If the first argument should appear after the second argument, a number greater than zero should be returned from the function.

• If both arguments are equivalent, zero should be returned from the function.

When the function specified by the sort() method returns zero, signifying that the arguments are equal, the arguments remain in the same order relative to each other after the function has been called.

Example

To help solidify how this method operates, Listing 7.75 demonstrates how to use the method to sort an array based on the number of characters in each argument. Notice how the sort() method changes the order of the elements of the array in Figure 7.5.

Listing 7.75 Sorting an Array Based on Argument Lengths

<script type=“text/javascript” language=“JavaScript”>

<!--
//Display the contents of an array.
function contentsOfArray(theArray)
{
    document.write("the array contains:<br>");
    //Access each element in the array.
    for(i=0; i<theArray.length; i++)
    {
       document.write("Position ",i," = ",theArray[i],"<br>");
    }
}

//Sort arguments based on their length.
function sortOnArgLen(arg1,arg2)
{
    if(arg1.length < arg2.length)
       return -1;
    if(arg1.length > arg2.length)
       return 1;
    if(arg1.length == arg2.length)
       return 0;
}

//Create and display an array of shapes.
shapes = new Array(“triangle”,“rectangle”,“square”);
document.write("Before the sort method ");
contentsOfArray(shapes);
//Sort the array.
shapes.sort(sortOnArgLen);
document.write("<br>After the sort method ");
contentsOfArray(shapes);
// -->
</script>

Figure 7.5 Sort the array elements based on the character length of each element.

Image

Array.splice()

JavaScript 1.2+, ECMAScript 3E+, JScript 5.5+

Nav4+, IE5.5+, Opera5+

 

Syntax

array.splice(start,delete,arg3,…,argN)

Description

The splice() method provides a way for elements to be either added or deleted from the array. When the delete parameter contains a number other than zero, the elements beginning at start and ending at start+delete are deleted from the array. If delete is zero, no elements are deleted. All elements from start to the end of the array are deleted when delete is not specified. If arguments follow the delete parameter, they are added to the array as elements beginning at the position specified by start. Existing elements are shifted up to allow room for the new elements.

NOTE
There was a bug in Navigator 4 when just one element was deleted from an array. Rather than returning an array that contained the deleted element, the actual element was returned from the method. In addition, when no elements were deleted from the array, null was returned instead of an empty array.

Table 7.17 lists the arguments and return values associated with the splice() method.

Table 7.17 Arguments and Return Values Associated with splice()

Image

Example

To help understand how the splice() method works, Listing 7.76 uses the delete and insert capabilities of the method to simulate a food order at a restaurant. In Figure 7.6, notice how the hamburger was replaced with a hot dog based on the customer’s change in appetite.

Listing 7.76 Using splice() to Simulate a Food Order

<script type=“text/javascript” language=“JavaScript”>
<!--
//Display the current order.
function printOrder(theArray)
{
    document.write("The current order is:<br>");
    //Access each element in the array.
    for(i=0; i<theArray.length; i++)
    {
       document.write("- ",theArray[i],"<br>");
    }
}

//Create and display a food order.
foodOrder = new Array(“hamburger”,“fries”,“drink”);
document.write("<h3>The initial order taken</h3>");
printOrder(foodOrder);

//Replace the hamburger with a hotdog.
foodOrder.splice(0,1,“hotdog”);
document.write("<h3>The customer wants a hotdog ");
document.write("instead of the hamburger.</h3>");

//Print the new order.
printOrder(foodOrder);
// -->
</script>

Figure 7.6 The food order changed using the splice() method.

Image

Array.toSource()

JavaScript1.3+, JScript3.0

Nav4.06+, IE4

 

Syntax

array.toSource()

Description

The toSource() method returns one string representing the source of the Array object. The string that is returned contains all the elements in the array separated with commas. The entire string is enclosed with brackets ([]) to show it is an array. If another array is contained within an array, its contents are also part of the string with its own set of brackets.

Example

Listing 7.77 creates an Array object of colors and an Array object of numbers. The array of numbers is included in the array of colors. The toSource() method is then applied to the Array object to return the source string.

[“Blue”, “Green”, “Red”, [3, 6, 7]]

Listing 7.77 Accessing the source of an Array object with the toSource() Method

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create an array of numbers.
numbers = new Array(3,6,7);
//Create an array of colors and a subarray of numbers.
colors = new Array(“Blue”,“Green”,“Red”,numbers);

//Force JavaScript to display the array contents in a string.
aString = colors.toSource();  //Create a string from the array contents.
document.write(aString); //Display the string.

// -->
</script>

Array.toString()

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, IE 4+, Opera5+

 

Syntax

array.toString()

Description

The toString()method returns one string that contains all the elements in the array separated with commas. You might be wondering why anyone would need this method when the join() method can do this and more. The reason is that the toString() method is what JavaScript uses to automatically convert an array to a string when the array is used in string context.

Table 7.18 shows the return value associated with the toString() method.

Table 7.18 Return Value Associated with toString()

Image

Example

Listing 7.78 creates an array of colors and then uses the toString() method to put the contents of the array into a string which is then displayed in the browser.

Listing 7.78 Forcing JavaScript to Use an Array’s toString() Method


<script type=“text/javascript” language=“JavaScript”>
<!-- 


//Create an array of colors.
colors = new Array(“Blue”,“Green”,“Red”);

//Force JavaScript to display the array contents in a string.
document.write(colors.toString()); //returns "Blue,Green,Red"
// -->
</script>

Array.unshift()

 

Syntax

array.unshift(arg1,…argN)

Description

The unshift() method adds the arguments listed in the parameter list to the front of the array as new elements. Existing elements are shifted up to allow room for the new elements. Table 7.19 lists the arguments and return values associated with this method.

Table 7.19 Arguments and Return Values Associated with unshift()

Image

Example

Listing 7.79 creates an array of school grades. Two new grades, 100 and 93, are added to the front of the array using the unshift() method. After the unshift() method has executed, the grades array contains [100,93,95,87], and newLength contains the new length of the array, 4.

Listing 7.79 Adding Elements to the Front of an Array Using the unshift() Method

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create an array of test grades.
grades = new Array(95,87);

//Add two more grades to the array.
newLength = grades.unshift(100,93);

//Display the grades stored in the array.
for(i=0; i<newLength; i++)
{
    document.write("grades[",i,"]=",grades[i],"<br>");
}

// -->
</script>

Array.unwatch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

Array.unwatch (property)

Description

The unwatch() method of the Array object, is used to turn off the watch on a particular property specified by property.

Example

Listing 7.80 shows how the unwatch() method is used to stop watching the user defined property p.

Listing 7.80 Example of the unwatch() method of the Array object

<script type=“text/javascript”  language=“JavaScript”>
<!--
function alertme(id,oldValue,newValue)
{
    document.writeln("myArray."  + id + " changed from " + oldValue + " to ");
    document.writeln(newValue + "<br>");
    return newValue;
}

var myArray = new Array();
Array.prototype.p = 1;
myArray.watch(“p”,alertme);

myArray.p = 2;
myArray.unwatch(“p”);
myArray.p = 3;
myArray.watch(“p”,alertme);
myArray.p = 4;
// -->
</script>

Array.valueOf()

JavaScript1.1+, ECMAScript 1E+, JScript3.0+

Nav3+, NES2+, IE4+, Opera3+

 

Syntax

array.valueOf ()

Description

The valueOf() method returns the primitive value of the object. In terms of an instance of an Array object, this method returns the array elements separated by commas. If an array contains another array, the contents are flattened when this method is used.

Example

Listing 7.81 creates an Array object of colors and an Array object of numbers. The array of numbers is included in the array of colors. Because the valueOf() method returns the actual elements in the array, "Blue,Green,Red,3,6,7" is written to the browser.

Listing 7.81 Using the valueOf() Method to Return the Value of the Array Object

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create an array of numbers.
numbers = new Array(3,6,7);

//Create an array of colors and a subarray of numbers.
colors = new Array(“Blue”,“Green”,“Red”,numbers);

//Display the primitive value of the array.
document.write(colors.valueOf()); //Display the array elements.

// -->
</script>

Array.watch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

Array.watch(property,function)

Description

The watch() method of the Array object is used to turn on the watch of a particular property specified by property. Any time the specified property is changed after the watch() method has been called, the specified function is called.

Example

Listing 7.82 shows how the watch() method is used to start watching the user-defined property p.

Listing 7.82 Example of the watch() Method of the Array Object

<script type=“text/javascript” language=“JavaScript”>
<!--
function alertme(id,oldValue,newValue)
{
    document.writeln("myArray." + id + " changed from " + oldValue + " to ");
    document.writeln(newValue + "<br>");
    return newValue;
}

var myArray = new Array();
Array.prototype.p = 1;
myArray.watch(“p”,alertme);

myArray.p = 2;
// -->
</script>

Automation

JScript3.0+

IE4+

 

Syntax

Core JScript Object

Description

Automation objects are objects that are connected to other applications or programming tools through automation interfaces. These objects give JScript developers access to properties and methods applications from within the JScript code. See ActiveXObject() and GetObject() for details on using automation objects.

Example

See ActiveXObject() and GetObject() for examples of using automation objects.

boolean

JavaScript1.2, ECMAScript 2E+, JScript 5+

Nav4+, NES3+, IE5+, Opera5+

 

Syntax

Reserved Keyword

Description

The boolean keyword has not been implemented in server-side JavaScript to date, but has been reserved for future use. Note that this keyword is not the same as the Boolean object.

Example

This keyword has not been implemented; therefore, no example is provided.

Boolean

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES3+, IE 4+, Opera5+

 

Syntax

var variable = new Boolean(value)
var variable = Boolean(value)

Description

The Boolean object is a wrapper object that holds a primitive boolean value, as well as provides a method for converting the value to a string. A primitive boolean can have only one of two states: true or false. Internally, JavaScript uses the number 1 to represent true and 0 to represent false, but provides the toString() method to return the strings “true” and “false”.

A Boolean object is created with the Boolean() constructor and the new operator or by the Boolean() function. The argument, return value, and method associated with this object are listed in Table 7.20.

Table 7.20 The Argument, Return Value, Properties, and Methods Associated with the Boolean Object

Image

Example

In Listing 7.83, a Boolean object and a primitive Boolean value are created. There are a couple of key points to notice when examining the results generated by the code, shown in Figure 7.7. First, the Boolean() constructor converts the string “false” to the Boolean value true. Second, boolObj is a Boolean object, whereas boolVal is just a variable holding a primitive Boolean value.

Listing 7.83 A Boolean Object Versus a Primitive Boolean Value

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a Boolean object.
boolObj = new Boolean(“false”);
document.write("boolObj = ",boolObj);         //Display true.
document.write(" [",typeof boolObj,"]<br>");  //Display object.

//Create a primitive boolean value.
boolVal = Boolean(false);
document.write("boolVal = ",boolVal);         //Display false.
document.write(" [",typeof boolVal,"]");      //Display boolean.

// -->
</script>

Figure 7.7 Boolean object versus primitive boolean value.

Image

Boolean.constructor

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES3+, IE 4+, Opera3+

 

Syntax

Boolean.constructor

Description

The constructor property of the Boolean object is used to create the object’s prototype.

Example

Listing 7.84 demonstrates the constructor property as it relates to the Boolean object.

Listing 7.84 The Boolean’s contructor Property

<script type=“text/javascript” language=“JavaScript”>
<!--
// Create a new boolean object using the constructor property.
myBoolean = new Boolean(true);
if(myBoolean.constructor == Boolean){
    document.write("Object was created");
}
// -->
</script>

Boolean.prototype

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, IE 4+, Opera5+

 

Syntax

Boolean.prototype.property
Boolean.prototype.method

Description

The prototype property allows you to add new properties and methods to the Boolean object that can be used throughout your code.

Example

In Listing 7.85, the prototype property is used to create a new method, called letter(), which can be used by all Boolean objects. The letter() method uses the letterBoolean() function to return true or false based on the status of the object.

Listing 7.85 Assigning a New Method to the Boolean Object with the prototype Property

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//This function returns the string “T” or “F” based on the value stored in the
//Boolean object that uses this function.
function letterBoolean()
{
    if(this == true)
       return(“T”);
    else
       return(“F”);
}

//Make the letterBoolean function available to all Boolean objects.
Boolean.prototype.letter = letterBoolean;

//Create a Boolean object with an initial setting of true.
var myBooleanObj = new Boolean(true);   //myBooleanObj equal to true

//Display the state of the Boolean object using the letter method.
document.write("myBooleanObj is set to ",myBooleanObj.letter());  //Return “T”

// -->
</script>

Boolean.toSource()

JavaScript1.3+, JScript3.0

Nav4.06+, IE4

 

Syntax

boolean.toSource()

Description

The toSource() method returns one string representing the source of the Boolean object. The string that is returned is enclosed in parentheses.

Example

Listing 7.86 creates a Boolean object to represent true. The toSource() method is then applied to the Boolean object to return the source string "(new Boolean(true))".

Listing 7.86 Accessing the Source of a Boolean Object with the toSource() Method


<script type=“text/javascript” language=“JavaScript”>
<!--
//Create a Boolean object representing true.
bool = new Boolean(1);

//Display the source of the Boolean object.
document.write(bool.toSource());

// -->
</script>

Boolean.toString()

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, IE 4+, Opera5+

 

Syntax

boolean.toString()

Description

The toString()method returns the string representation (“true” or “false”) of the primitive Boolean value stored in the Boolean object. The return value associated with this object is listed in Table 7.21.

Table 7.21 Return Value Associated with toString()

Image

Example

In Listing 7.87, the toString() method is used to force a comparison of strings rather than Boolean values. Without the toString() method, the if comparison would find the Boolean value not equal to the string value.

Listing 7.87 Force the Desired Comparison Using Boolean ’s toString() Method

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a Boolean object that contains the boolean value “false”.
boolObj = new Boolean(false);

//Force JavaScript to convert the boolObj object to the string “false”
//before comparing to the string “false”.
if(boolObj.toString() == “false”)     //Evalutes to true,
    alert(“EQUAL”);                     //so display “EQUAL” on screen.

else
alert("NOT Equal");

// -->
</script>

Boolean.unwatch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

Boolean.unwatch(property)

Description

The unwatch() method of the Boolean object is used to turn off the watch on a particular property specified by property.

Example

Listing 7.88 shows how the unwatch() method is used to stop watching the user-defined property p.

Listing 7.88 Example of the unwatch() method of the Boolean Object

<script type=“text/javascript” language=“JavaScript”>
<!--
function alertme(id,oldValue,newValue)
{
    document.writeln("myBoolean." + id + " changed from " + oldValue + " to ");
    document.writeln(newValue + "<br>");
    return newValue;
}

var myBoolean = new Boolean();
Boolean.prototype.p = 1;
myBoolean.watch(“p”,alertme);

myBoolean.p = 2;
myBoolean.unwatch(“p”);
myBoolean.p = 3;
myBoolean.watch(“p”,alertme);
myBoolean.p = 4;
// -->
</script>

Boolean.valueOf()

JavaScript1.1+, ECMAScript 1E+, JScript3.0+, Nav3+, NES2+, IE4+, Opera3+

 

Syntax

boolean.valueOf()

Description

The valueOf() method returns the primitive value of the object. In terms of an instance of a Boolean object, this method returns a Boolean value contained in the object.

Example

Listing 7.89 creates a Boolean object representing true. Because the valueOf() method returns the Boolean value in the object, “true” is written to the browser.

Listing 7.89 Using the valueOf() Method to Return the Value of the Boolean Object

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a Boolean object representing true.
bool = new Boolean(1);

//Display the source of the Boolean object.
document.write(bool.valueOf());

// -->
</script>

Boolean.watch()

JavaScript 1.2+

Nav4+, NES3+

 

Syntax

Boolean.watch (property,function)

Description

The watch()method of the Boolean object is used to turn on the watch of a particular property specified by property. Any time the specified property is changed after the watch() method has been called, the specified function is called.

Example

Listing 7.90 shows how the watch() method is used to start watching the user-defined property p.

Listing 7.90 Example of the watch() Method of the Boolean Object


<script type=“text/javascript” language=“JavaScript”>
<!--
function alertme(id,oldValue,newValue)
{
    document.writeln("myBoolean." + id + " changed from " + oldValue + " to ");
    document.writeln(newValue + "<br>");
    return newValue;
}

var myBoolean = new Boolean();
Boolean.prototype.p = 1;
myBoolean.watch(“p”,alertme);

myBoolean.p = 2;
// -->
</script>

break

JavaScript 1.1+, ECMAScript 1E+, JScript 1.0+

Nav3+, IE 3+, Opera3+

 

Syntax

break label;

Description

The keyword break provides a way to exit out of loop structures and switch conditionals prematurely. Most of the time, the word break appears on a line by itself, but there are times when a label will follow the keyword (see Table 7.22). When a label is used, code execution completely breaks out of the area designated by label and proceeds to the code that follows the area. To label a statement, simply place the label name followed by a colon (:) in front of the code that needs to be broken out of during code execution.

Table 7.22 Argument Associated with the break Keyword

Image

Example

Listing 7.91 demonstrates the effect of using labels and break statements when working with nested loops. Figure 7.8 shows the result of executing this code.

Listing 7.91 Using break s and Labels


<script type=“text/javascript” language=“JavaScript”>
<!--

//Loop through the outer loop (forLoop1) 4 times.
forLoop1:
for (var counter1 = 1; counter1 <= 5; counter1++)
{
    //Go through this inner loop 4 times for each time through the outer loop.
    for (var counter2 = 1; counter2 <= 5; counter2++)
    {
       //Display the values in each for loop’s counter.
       document.write("Counter1=",counter1);
       document.write(" Counter2=",counter2,"<br>");

       //Break out of inner loop the 3rdtime through the inner loop.
       if (counter2 == 3)
      break;

       //Break out of the outer loop the 3rdtime through the outer loop.
       if (counter1 == 3)
      break forLoop1;
    }
}

document.write("All done!");

//-->
</script>

Figure 7.8 Using labels and thebreak statement in nested loops.

Image

Notice how the break statement with no label, in Figure 7.8, breaks out of just the inner loop. When the break statement is used with a label, JavaScript knows at what level to break.

byte

JavaScript1.2+, ECMAScript 2E+, JScript 5+

Nav4+, NES3+, IE5+, Opera5+

 

Syntax

Reserved Keyword

Description

The byte keyword has not been implemented in server-side JavaScript to date, but has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

case

JavaScript1.2+, ECMAScript 2E+, JScript3.0+

Nav4+, NES3+, IE4+, Opera5+

 

Syntax

Reserved Keyword

Description

The case keyword has not been implemented in server-side JavaScript to date, but has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

char

JavaScript1.2+, ECMAScript 2E+, JScript 5+

Nav4+, NES2+, IE5+, Opera5+

 

Syntax

Reserved Keyword

Description

The char keyword has not been implemented in server-side JavaScript to date, but has been reserved for future use.

Example

This keyword has not been implemented; therefore, no example is provided.

class

JavaScript1.2+, ECMAScript 1E+, JScript3.0+

Nav4+, NES3+, IE4+, Opera5+

 

Syntax

Reserved Keyword

Description

The word class is reserved for future use, so there is no definition at this time.

Example

No example can be provided because class is reserved for future use.

const

 

JavaScript1.2, ECMAScript 1E+, JScript 5+
Nav4+, NES3+, IE5+, Opera5+

 

Syntax

Reserved Keyword

Description

The word const is reserved for future use, so there is no definition at this time.

Example

No example can be provided because const is reserved for future use.

continue

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, IE 4+, Opera3+

 

Syntax

continue label;

Description

The continue statement forces the execution of the code within a loop to continue at the beginning of the loop. Normally, the continue keyword appears on a line by itself, but there are times when a label will follow the keyword (see Table 7.23). When a label is used, code execution immediately jumps to the beginning of the loop designated by the label and begins executing code.

Table 7.23 Argument Associated with the continue Keyword

Image

The beginning of a loop varies depending on the type of loop structure. Table 7.24 shows where each looping structure jumps to when a continue structure is encountered.

Table 7.24 Where the continue Statement Jumps

Image

To label a statement, simply place the label name followed by a colon (:) in front of the code where code execution needs to continue.

Example

Listing 7.92 demonstrates the use of labels and continue. This example is a bit complicated, so take time to compare Listing 7.79 to the output in Figure 7.9. Notice how the phrase "Bottom of innerLoop" was not printed after the "Continue at top of innerLoop." because code execution jumped back to beginning of the inner-most loop. When a label was attached to the continue keyword, code execution jumped back to the beginning of the loop labeled outerLoop.

Listing 7.92 Using the continue Statement


<script type=“text/javascript” language=“JavaScript”>
<!--

//Loop through the outerLoop twice.
outerLoop:
    for (var counter1 = 1; counter1 <= 2; counter1++)
    {
       document.write("Top of outerLoop.<br>");

       //Loop through the innerLoop twice.
       innerLoop:
      for (var counter2 = 1; counter2 <= 2; counter2++)
      {
       //Display the values in each for loop’s counter.
       document.write("Top of innerLoop.<br>");
       document.write("Counter1=",counter1,"<br>");
       document.write("Counter2=",counter2,"<br>");

       //If this is the second time through the innerLoop,
       //don’t go any further and jump back to the top of the innerLoop.
       if (counter2 == 2)
       {
         document.write("Continue at top of innerLoop.<br>");
         continue;
       }

       //If this is the second time through the outerLoop,
       //don’t go any further and jump back to the top of the outerLoop.

       if (counter1 == 2)
       {
         document.write("Continue at top of outerLoop.<br>");
         continue outerLoop;
       }
       document.write("Bottom of innerLoop.<br>");
      }
       document.write("Bottom of outerLoop.<br>");
    }

document.write("All done!");

//-->
</script>

Figure 7.9 The result of using the continue statement.

Image

Date

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

var variable = new Date(); 
var variable = new Date(milliseconds1); 
var variable = new Date(string) var variable = new Date(yearmonthdayhoursminutessecondsmilliseconds2)

Description

The Date object represents all aspects of a date and time from year to milliseconds. If arguments are provided when creating the Date object, the new object will contain the date specified; otherwise the object will be set to the current date. The arguments and methods are listed in Table 7.25.

Table 7.25 Arguments and Methods Associated with the Date Object

Image

Image

Image

Example

Listing 7.93 demonstrates how to create Date objects using various arguments in the Date() constructor.

Listing 7.93 Creating Date Objects

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a new Date object using all arguments.
theDate1 = new Date(2002,9,29,20,5,8,10);

//Create a new Date object using just milliseconds.
theDate2 = new Date(theDate1.getTime());

//Create a new Date object using a string.
theDate3 = new Date(theDate1.toString());

//Display all the date objects.
document.write("theDate1-> ",theDate1.toString());
document.write("<br>theDate2-> ",theDate2.toString());
document.write("<br>theDate3-> ",theDate3.toString());

// -->
</script>

Date.constructor

JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+

Nav3+, NES3+, IE 4+, Opera3+

 

Syntax

Date.constructor

Description

The constructor property of the Date object is used to create the object’s prototype.

Example

Listing 7.94 demonstrates the constructor property as it relates to the Date object.

Listing 7.94 The Date ’s contructor Property


<script type=“text/javascript” language=“JavaScript”>
<!--
// Create a new date object using the constructor property.
myDate = new Date();
if(myDate.constructor == Date){
    document.write("Object was created");
}
// -->
</script>

Date.getDate()

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

date.getDate ()

Description

The getDate()method returns the day of the month expressed as an integer from 1 to 31.

Example

The code in Listing 7.95 displays the current day of the month expressed as an integer from 1 to 31 using the getDate() method.

Listing 7.95 Using the getDate() Method to Return the Day of the Month


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a Date object that contains the current date and time.
theDate = new Date();

//Display the date.
document.write("The date is ",theDate.getDate());

// -->
</script>

Date.getDay()

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

date.getDay()

Description

The getDay()method returns the day of the week expressed as an integer from 0 (Sunday) to 6 (Saturday).

Example

The code in Listing 7.96 uses the getDay() method to return the day of the week expressed as an integer. This number is then converted to a string representation of the day of the week.

Listing 7.96 Using the getDay() Method to Return the Day of the Week


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//This function converts the day from a number to
//a string and returns the string.
function getDayString(num)
{
    var day;    //Create a local variable to hold the string.
    switch(num)
    {
       case 0:
      day=“Sunday”;
      break;
       case 1:
      day=“Monday”;
      break;
       case 2:
      day=“Tuesday”;
      break;

       case 3:
      day=“Wednesday”;
      break;
       case 4:
      day=“Thursday”;
      break;
       case 5:
      day=“Friday”;
      break;
       case 6:
      day=“Saturday”;
      break;
       default:
      day="Invalid day";
    }
    return day;
}

//Create a Date object that contains the current date and time.
theDate = new Date();

//Display the day.
document.write("Today is ",getDayString(theDate.getDay()));
// -->
</script>

Date.getFullYear()

JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+,br/>Nav4+, IE 4+, Opera5+

 

Syntax

date.getFullYear()

Description

The getFullYear()method returns the year in local time as a full four-digit number.

Example

The code in Listing 7.97 displays the year using the getFullYear() method.

Listing 7.97 Using the getFullYear() Method to Return the Year

<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a Date object that contains the current date and time.
theDate = new Date();

//Display the full year.
document.write("The year is ",theDate.getFullYear());

// -->
</script>

Date.getHours()

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

date.getHours()

Description

The getHours() method returns the hour portion of the date expressed as an integer from 0 (12:00 a.m. midnight) to 23 (11:00 p.m.).

Example

The code in Listing 7.98 displays the current hour as an integer from 0 to 23 using the getHours() method.

Listing 7.98 Using the getHours() Method to Return the Current Hour


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a Date object that contains the current date and time.
theDate = new Date();

//Display the hour.
document.write("The hour is ",theDate.getHours());

// -->
</script>

Date.getMilliseconds()

JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+

Nav4+, IE 4+, Opera5+

 

Syntax

date.getMilliseconds()

Description

The getMilliseconds() method returns the millisecond portion of the date expressed as an integer from 0 to 999.

Example

The code in Listing 7.99 displays the milliseconds in the Date object using the getMilliseconds() method.

Listing 7.99 Using the getMilliseconds() Method to Return the Current Millisecond


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a Date object that contains the current date and time.
theDate = new Date();

//Display the milliseconds.
document.write("The millisecond is ",theDate.getMilliseconds());

// -->
</script>

Date.getMinutes()

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

date. getMinutes()

Description

The getMinutes() method returns the minutes portion of the Date object expressed as an integer from 0 to 59.

Example

The code in Listing 7.100 displays the current minute using the getMinutes() method.

Listing 7.100 Using the getMinutes() Method to Return the Current Minute


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a Date object that contains the current date and time.
theDate = new Date();

//Display the minutes.
document.write("The minute is ",theDate.getMinutes());

// -->
</script>

Date.getMonth()

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

date.getMonth()

Description

The getMonth() method returns the month portion of the Date object expressed as an integer from 0 (January) to 11 (December).

Example

The code in Listing 7.101 displays the current month using the getMonth() method.

Listing 7.101 Using the getMonth() Method to Return the Current Month


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//This function converts the month from a number to
//a string and returns the string.
function getMonthString(num)
{
    var month;    //Create a local variable to hold the string.
    switch(num)
    {
       case 0:
      month=“January”;
      break;
       case 1:
      month=“February”;
      break;
       case 2:
      month=“March”;
      break;
       case 3:
      month=“April”;
      break;
       case 4:
      month=“May”;
      break;
       case 5:
      month=“June”;
      break;
       case 6:
      month=“July”;

      break;
       case 7:
      month=“August”;
      break;
       case 8:
      month=“September”;
      break;
       case 9:
      month=“October”;
      break;
       case 10:
      month=“November”;
      break;
       case 11:
      month=“December”;
      break;
       default:
      month="Invalid month";
    }
    return month;
}

//Create a Date object that contains the current date and time.
theDate = new Date();

//Display the month.
document.write("The month is ",getMonthString(theDate.getMonth()));

// -->
</script>

Date.getSeconds()

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

date.getSeconds()

Description

The getSeconds() method returns the seconds portion of the Date object expressed as an integer from 0 to 59.

Example

The code in Listing 7.102 displays the current seconds using the getSeconds() method.

Listing 7.102 Using the getSeconds() Method to Return the Current Second


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a Date object that contains the current date and time.
theDate = new Date();

//Display the seconds.
document.write("The second is ",theDate.getSeconds());

// -->
</script>

Date.getTime()

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

date.getTime()

Description

The getTime() method returns the equivalence of the Date object in milliseconds. The milliseconds are expressed as an integer representing the number of milliseconds between midnight January 1, 1970 (GMT) to the date and time specified in the Date object.

Example

The code in Listing 7.103 displays, 946684800000, the number of milliseconds that passed between midnight January 1, 1970 and midnight January 1, 2000 using the getTime() method.

Listing 7.103 Using the getTime() Method to Return the Milliseconds Between 1970 and 2000


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a Date object that contains midnight January 1, 1970.
Date1970 = new Date(1970,1,1,0,0,0,0);


//Create a Date object that contains midnight January 1, 2000.
date2000 = new Date(2000,1,1,0,0,0,0);
//Display the elapsed milliseconds.
document.write(date2000.getTime()-date1970.getTime());
document.write(" milliseconds passed between 1-1-1970 and 1-1-2000");

// -->
</script>

Date.getTimezoneOffset()

JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+

Nav2+, NES2+, IE 3+, Opera3+

 

Syntax

date.getTimezoneOffset()

Description

The getTimezoneOffset() method returns the difference between the time zones of local time and Greenwich Mean Time (GMT). This difference is returned as an integer representing the number of minutes between the time zone of the local time and GMT. Although this is a method of a Date object, the actual date and time associated with the date is irrelevant because the time zone difference is based on the environment settings in which the JavaScript code is run.

Example

The code in Listing 7.104 displays the time zone offset by using the getTimezoneOffset() method. Notice that when the date and time are changed, the time zone offset remains the same because the contents of the Date object are not used in the calculation.

Listing 7.104 Using the getTimezoneOffset() Method to Return the Time Zone Offset


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create 2 very different date objects.
aDate1 = new Date(1990,1,1,0,0,0,0);
aDate2 = new Date(1994,2,13,8,24,45,300);

//Display the timezone offsets.
document.write("The timezone offset of aDate1 is ");
document.write(aDate1.getTimezoneOffset()," minutes.<br>");
document.write("The timezone offset of aDate2 is "
document.write(aDate2.getTimezoneOffset()," minutes.");

// -->
</script>

Date.getUTCDate()

JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+

Nav4+, IE 4+, Opera5+

 

Syntax

date.getUTCDate()

Description

The getUTCDate() method returns the day of the month converted to universal time and expressed as an integer from 1 to 31.

Example

The code in Listing 7.105 displays the day of the month in universal time using the getUTCDate() method.

Listing 7.105 Using the getUTCDate() Method to Return the Day of the Month


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//Create a Date object that contains the current date and time.
theDate = new Date();

//Display the UTC date.
document.write("The UTC date is ",theDate.getUTCDate());

// -->
</script>

Date.getUTCDay()

JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+

Nav4+, IE 4+, Opera3+

 

Syntax

date.getUTCDay()

Description

The getUTCDay() method returns the day of the week converted to universal time and expressed as an integer from 0 (Sunday) to 6 (Saturday).

Example

The code in Listing 7.106 uses the getUTCDay() method to return the day of the week expressed as an integer in universal time. The number is then converted to a string equivalent to the day of the week.

Listing 7.106 Using the getUTCDay() Method to Return the Day of the Week


<script type=“text/javascript” language=“JavaScript”>
<!-- 

//This function converts the day from a number to
//a string and returns the string.
function getDayString(num)
{
    var day;    //Create a local variable to hold the string.
    switch(num)
    {
       case 0:
      day=“Sunday”;
      break;
       case 1:
      day=“Monday”;
      break;
       case 2:
      day=“Tuesday”;
      break;
       case 3:
      day=“Wednesday”;
      break;
       case 4:
      day=“Thursday”;
      break;
       case 5:
      day=“Friday”;
      break;
       case 6:
      day=“Saturday”;
      break;
       default:
      day="Invalid day";
    }
    return day;
}

//Create a Date object that contains the current date and time.
theDate = new Date();

//Display the UTC day.
document.write("The UTC day is ",getDayString(theDate.getUTCDay()));

// -->
</script>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.64.132