What's New in JavaScript 1.3

This document describes the new features and changes in JavaScript 1.3. The focus here is on the JavaScript core language and its implementation in Netscape Communicator/Navigator 4.06 and 4.5. This document supplements the existing documentation for JavaScript 1.2. The changes in JavaScript 1.3 are minor. You should easily be able to convert your existing code with little modification.

For information about JavaScript 1.2, see the JavaScript Guide and the JavaScript Reference Manual. Additional information can also be found under the DevEdge Online's JavaScript Documentation.

The most significant change to this version of JavaScript is its compliance with the European Computer Manufacturers Association specification, ECMA-262, and the International Organization for Standards specification, ISO-16262. Therefore, this document begins with a brief discussion of JavaScript and ECMA, including a comparison between JavaScript 1.3 and the current version of the ECMA specification.

This document also describes the following new feature and changes to JavaScript 1.3. Some of these features reflect the current ECMA-262. Others anticipate the next release of the ECMA standard, ECMAScript 2.0.

New Features

Changes

Supplements to JavaScript Manual

Communicator/Navigator 4.06 and 4.5 also support a new feature, JavaScript console that records JavaScript error messages.

JavaScript and ECMA

JavaScript is the cross-platform, object-based scripting language for Netscape client and server applications. The JavaScript core language contains the elements common to both client-side and server-side JavaScript. ECMA specification is based on the core language of JavaScript, which is a subset of JavaScript language.

Netscape chose ECMA for delivering a standard, international programming language based on JavaScript. ECMA is the international standards association for information and communication systems. The standardization of JavaScript means that, when you write JavaScript code, it will behave in the same way on all applications that support the standard. JavaScript is now a mature language that can be used for a variety of tasks. Companies can use the same open standard language to develop their implementation of JavaScript.

ECMA completed the first version of the specification, ECMAScript, in June 1997. (In this document, when the ECMA specification or ECMA-262 is used, it refers to the specification dated June 1997.) ECMAScript, as defined by the ECMA, is an object-oriented programming language for performing computations and manipulating objects within a host environment. More recently, the ECMA-262 standard was also approved by ISO. You can find a PDF version of this standard at Netscape DevEdge Online. You can also find the specification under the ECMA Web site. (Note that ECMA does not specify the Document Object Model (DOM), which is being standardized by W3C. DOM defines the way in which the HTML document objects are exposed to your script.)

The ECMA specification adds two special features to the JavaScript: internationalization, using Unicode discussed below, and uniform JavaScript behavior across all platforms. A number of features of previous versions of JavaScript, such as the Date object, were platform-dependent and used platform-specific behavior.

Netscape worked closely with ECMA to produce the ECMA specification. The ECMA specification is based on JavaScript 1.1. When Netscape Navigator 4.0 was released, the ECMA standard had not yet been finalized. Netscape had developed additional features in JavaScript 1.2 that were not considered by the ECMA. Thus, JavaScript 1.2, the version in Communicator Navigator 4.0-4.05, was not fully compatible with ECMA-262. JavaScript 1.3 resolves this inconsistency, while keeping all the additional features of JavaScript 1.2. These additional features, including some new features of JavaScript 1.3 that are not part of ECMA, are under consideration for next version of ECMA standard. You should expect most features of JavaScript 1.3 to become part of ECMAScript 2.0. For example, JavaScript 1.2 and 1.3 support regular expression, which is not included in the June 1997 ECMA specification. Regular expressions are a powerful feature of JavaScript that can help in finding and replacing matches in string.

JavaScript will continue to lead the way in enhancing and extending the language. It will always include advanced features not part of ECMA standard. JavaScript is compatible with ECMA, while providing additional features.

Comparison between JavaScript 1.3 and ECMA-262

The JavaScript Reference Guide is a language reference guide for programmers who use JavaScript, whereas the ECMA specification is actually a set of requirements for implementing ECMAScript. As such, the use of the ECMA document is not appropriate for those who want to learn to program scripts using either JavaScript or any other implementation of ECMA-262. The ECMA specification is useful if you want to verify that a JavaScript feature is supported under ECMA-262. If you plan to write JavaScript code that uses only features supported by the ECMA, then you may need to review the ECMA specification.

The ECMA specification may use terminology and syntax unfamiliar to a JavaScript programmer. Although the description of the language may differ in ECMA-262, the language itself remains the same. JavaScript 1.3 supports all the ECMA-262 functionality.

The JavaScript documentation describes the aspects of the language that are appropriate for a JavaScript programmer. For example, global object, which contains the global methods, is defined in ECMA. But, because you do not use the global object (top-level object) directly, it is not discussed in the JavaScript documentation. The methods of the global object (global methods), which you will use, are discussed in the JavaScript documentation. You reference these top-level methods (for example, isNaN or parseInt) directly. Another example is the use of no parameter (zero-argument) constructor with the Number and String objects. This constructor is not documented in the JavaScript Reference manual, because what is generated is of little use. A Number constructor without an argument returns +0 and a String constructor without an argument returns "", an empty string.

The following is a list of the features in the JavaScript 1.3 core language that are not in the current ECMA specification. These value-added extensions to the language are expected in the next version of ECMA specification. Some of these features are new to JavaScript 1.3 and are discussed in this document. Others are supported by JavaScript 1.3, but are already part of JavaScript 1.2 and are documented in the JavaScript 1.2 Reference Manual.

Non-ECMA-262 features of JavaScript 1.3

Specifying the Version of JavaScript

You can use the LANGUAGE attribute with the <SCRIPT> tag to specify the version of JavaScript with which the script complies. For example, to use JavaScript 1.2 syntax, you can specify <SCRIPT LANGUAGE="JavaScript1.2">. If you do not specify a LANGUAGE attribute, the default behavior for Navigator 4.06 and 4.5 is to support JavaScript 1.3. Earlier browsers use the latest version of JavaScript supported by the browser.

Using the LANGUAGE tag attribute, you can write scripts compliant with earlier version of Netscape Navigator or Communicator. You can write different scripts for the different versions of the browser. If the specific browser does not support the specified JavaScript version, the code is ignored.

The following is a list of the JavaScript SCRIPT tags supported by different Netscape browsers.

New Features

The following features and enhancements are new to JavaScript 1.3. The most significant new feature in JavaScript 1.3 is the support of Unicode. With the exception of the toSource, apply, and call methods, the following enhancements are made to comply with ECMA-262. The toSource, apply, and call methods have been proposed for the next release of the ECMA specification.

Unicode

Unicode is a universal character-coding standard for the interchange and display of principal written languages. It covers the languages of Americas, Europe, Middle East, Africa, India, Asia, and Pacifica, as well as historic scripts and technical symbols. Unicode allows for the exchange, processing, and display of multilingual texts, as well as the use of common technical and mathematical symbols. It hopes to resolve internationalization problems of multilingual computing, such as different national character standards. Not all modern or archaic scripts, however, are currently supported.

The Unicode standard is a fixed-width uniform encoding scheme. The same unified character set can be used for all known encoding. Unicode is modeled after the ASCII (American Standard Code for Information Interchange) character set. It uses a numerical value and name for each character. The character encoding specifies the identity of the character and its numeric value (code position), as well as the representation of this value in bits. The 16-bit numeric value (code value) is defined by a hexadecimal number and a prefix U, for example, U+0041 represents A. The unique name for this value is LATIN CAPITAL LETTER A.

Unicode is compatible with ASCII characters and is supported by many programs. The first 128 Unicode characters correspond to the ASCII characters and have the same byte value. The Unicode characters U+0020 through U+007E are equivalent to the ASCII characters 0x20 through 0x7E. Unlike ASCII, which supports the Latin alphabet and uses 7-bit character set, Unicode uses a 16-bit value for each character. It allows for more than 65,000 unique characters. Unicode version 2.0 contains 38,885 characters. It also supports an extension mechanism, Transformation Format (UTF), named UTF-16, that allows for the encoding of one million more characters by using 16-bit character pairs. UTF turns the encoding to actual bits. Unicode is fully compatible with the International Standard ISO/IEC 10646-1; 1993, which is a subset of ISO 10646, and supports the ISO UCS-2 (Universal Character Set) that uses two-octets (two-bytes or 16-bits).

JavaScript and Communicator/Navigator support for Unicode means you can use non-Latin, international and localized characters, plus special technical symbols in JavaScript programs. Unicode provides a standard way to encode multilingual text. Since Unicode is compatible with ASCII, programs can use ASCII characters. You can use Non-ASCII Unicode characters in the comments and string literals of JavaScript.

In string literals, you can also use the Unicode escape sequence, which consists of six ASCII characters. The escape sequence comprises of \u and a four digit hexadecimal number. For example, \u0041 represents the Unicode character A. Every Unicode escape sequence in JavaScript adds only one character to the string value.

The JavaScript use of the Unicode escape sequence is different from Java. In JavaScript, the escape sequence is never interpreted as a special character first. In other words, a line terminator escape sequence inside a string does not terminate the string before it is interpreted by the function. JavaScript ignores any escape sequence if it is used in the comments. In Java, if an escape sequence is used in a single comment line, it is interpreted as an Unicode character. For a string literal, Java Interpreter interprets the escape sequences first. In other words if a line terminator escape character (\u000A) is used in Java, it terminates the string literal. In Java, this leads to an error, because line terminators are not allowed in string literals. You must use \n for a line feed in a string literal. In JavaScript, the escape sequence works the same way as the \n.

The following code, when invoked, generates an information dialog box with the copyright symbol and the string "Netscape Communication".

alert("\u00A9 Netscape Communication");

The following table lists frequently used special characters and their Unicode value.

\

Unicode Value

Name

Format Name

White Space Values

\u0009

Tab

<TAB>

\u000B

Vertical Tab

<VT>

\u000C

Form Feed

<FF>

\u0020

Space

<SP>

Line Terminator Values

\u000A

Line Feed

<LF>

\u000D

Carriage Return

<CR>

Additional Unicode Escape Sequence Values

\u000b

Backspace

<BS>

\u0009

Horizontal Tab

<HT>

\u0022

Double Quote

"

\u0027

Single Quote

Ď

\u005C

Backslash

\

You can use Unicode to display the characters in different languages or technical symbols. For characters to be displayed properly, a client such as Netscape Navigator 4.x needs to support Unicode. Moreover, an appropriate Unicode font must be available to the client, and the client platform must support Unicode. Often, Unicode fonts do not display all the Unicode characters. Some platforms, such as Windows 95, provide a partial support for Unicode.

To receive Non-ASCII character input, the client needs to send the input as Unicode. Using a standard enhanced keyboard, the client cannot easily input the additional characters supported by Unicode. Often, the only way to input Unicode characters is by using Unicode escape sequences. The Unicode specification, however, does not require the use of escape sequences. Unicode delineates a method for rendering special Unicode characters using a composite character. It specifies the order of characters that can be used to create a composite character, where the base character comes first, followed by one or more non-spacing marks. Common implementations of Unicode, including the JavaScript implementation, however, do not support this option. JavaScript does not attempt the representation of the Unicode combining sequences. In other words, an input of a and ` does not produce à. JavaScript interprets a` as two distinct 16-bit Unicode characters. You must use a Unicode escape sequence or a literal Unicode character for à.

For more information on Unicode see the Unicode Consortium Web site) and The Unicode Standard, Version 2.0, published by Addison-Wesley, 1996.

New Top-level Properties

The following three properties are defined as properties of the global object. They are also primitive values. (See section JavaScript Terms, below, for a description of primitive values.)

NaN

Syntax

NaN

Description

NaN represents the IEEE (Institute of Electrical and Electronics Engineers) standard set "Not-a-Number", an IEEE floating point reserved for Not-a-Number value. In JavaScript 1.2, NaN was only defined as property of the Number object. In 1.3, it is also defined as a property of global object. In other words, it is available as a top-level property, when the JavaScript engine is initialized. The initial value of NaN is NaN.

NaN is always unequal to any other number, including NaN itself. You should use the method isNaN to check for a NaN value. A number of JavaScript methods (such as Number constructor, parseFloat, and parseInt) return NaN, if the value specified in the parameter is not a number, a well-formed numeric literal.

Infinity

Syntax

Infinity

Description

Infinity is a primitive value that represents a positive infinite number value. In JavaScript 1.2, Infinity was only defined as the property of the Number object. The actual properties of the Number object for infinity are the static properties POSITIVE_INFINITY and NEGATIVE_INFINITY (for example, Number.NEGATIVE_INFINITY). In JavaScript 1.3, Infinity is defined as the property of the global object and is available when the JavaScript engine is initialized. It is available as a top-level property. The initial value of Infinity is Number.POSITIVE_INFINITY. The value Infinity (positive infinity) is greater than any other number including itself. This value behaves mathematically like infinity; for example, anything multiplied by Infinity is Infinity, and anything divided by Infinity is 0.

undefined

Syntax

undefined

Description

undefined is a primitive value. In other words, it is represented at the lowest level of language. This value was not previously defined in JavaScript 1.2. A variable that has not been assigned a value is of type undefined. You can use undefined to verify if a variable does not have a value. A JavaScript method or statement also returns undefined, if the variable that is being evaluated does not have an assigned value.

undefined is also a property of the global object, whose value is undefined primitive value. Note that under ECMA-262, undefined is only defined as a primitive value and not a property of the global object.

Example

In the code below, since the variable input is not defined, the if statement is evaluated to true.


var input;
if(input == undefined){
   document.write("input is not defined.");
}

Global Function isFinite

Syntax

isFinite(number)

Parameter

number (the number you wish to evaluate)

Description

isFinite is a new global function, a top level function property of the global object. You can use this function to determine if a number is a finite number. isFinite function examines the number in its argument. If the argument is NaN, positive infinity or negative infinity, this method returns false, otherwise it returns true.

Example

You can check a client input to verify if it is a finite number.

if(isFinite(ClientInput) == true)

{

    /* take specific steps */

}

toSource method

Syntax

toSource()

Parameter

None

Description

This is a new method and is not currently in ECMA-262. It has been proposed for the next release of ECMA specification. The toSource method is defined for all built-in core JavaScript objects. Most objects derive this method from Object. This method is based on the toString method of the Object and Array objects. You can use it to create a copy of an object. Unlike toString method, toSource enumerates through the properties of the object. For example, while toString returns [object Object] for an Object, toSource returns an object literal (See section JavaScript Terms, below, for more information on object literals.)

toSource returns a string representation of the object, which you can use to create a new object. You can pass the returned string to eval, save it, etc. For Object tools, method eval(tools.toSource()) returns a value equivalent to a copy of tools. If tools has recursive properties (properties that refer to itself), the string returned by toSource may look strange. It will reflect the temporary variables used for the recursive value. (See also toString.)

Example

product = {type: "electronic", value: 500};
myList = ["school", 4, "home", 10];
myBool = new Boolean; 
myString = new String("my line");
myDate = new Date();
document.write(product.toSource());  // writes the object literal 

                                     // {type:"electronic", value:500}

document.write(myList.toSource());   // writes the array literal

                                     // ["school", 4, "home", 10]



document.write(myBool.toSource());   // writes (new Boolean(false))

document.write(myString.toSource()); // writes (new String("source"))

document.write(myDate.toSource()); // writes 

                                   // (new Date([the date in millisecond]))

Date Object

The Date object in JavaScript 1.3 has changed significantly to conform to ECMA specification. Therefore, the new and changed Date object features are discussed as part of the new features of JavaScript 1.3.

Date object in previous version of JavaScript depended on platform-specific date facilities and behavior. The new ECMA-conformant implementation of Date removes all previous platform dependencies and provides a uniform behavior across platforms.

The Date object now supports a number of new Universal Coordinated Time methods (UTC methods), as well as local time methods. UTC, also known as Greenwich Mean Time (GMT), refers to the time as set by the World Time Standard. The local time is the time known to the computer where the JavaScript is executed.

Date is measured in milliseconds since midnight 01 January, 1970 UTC. A day holds 86,400,000 milliseconds. The Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.

The following example returns the time elapsed between timeA and timeB in milliseconds.

timeA = new Date(); 

// Take any specific action. Here is an example.

alert("measuring wait period");

timeB = new Date(); 

timeDifference = timeB - timeA; 

The JavaScript 1.3 Date object's compound constructor now allows you to specify an instance of time in milliseconds. Previously, you could only specify the time in milliseconds with the Date constructor that supports a number as a parameter.

Aside from the constructors and UTC methods that support milliseconds, the methods getMilliseconds and setMilliseconds, along with getUTCMilliseconds and setUTCMilliseconds, have also been added. getMilliseconds returns the millisecond past the second from the millisecond stored in the Date object. setMilliseconds sets the value of milliseconds for a specified Date object. The getUTCMilliseconds and setUTCMilliseconds methods use a date based on UTC instead of a date based on local time.

For compatibility with millenium calculations (in other words, to take into account the year-2000), you should always specify the year in full. In other words, use 1998 not 98. To assist you in specifying the complete year, JavaScript includes new methods, setFullYear and getFullYear, along with setFullUTCYear and getFullUTCYear. getFullYear returns the absolute year number, for example, 1998. setFullYear, sets the full (absolute) year for a specified date. Use these methods instead of getYear and setYear methods. getYear and setYear are supported for backwards compatibility only.

New Constructor

The compound constructor for the Date object now supports milliseconds (ms_num). To specify the milliseconds, use the following constructor.

Date(yr_num, mo_num, day_num, hr_num, , min_num, sec_num, ms_num)

The new Syntax for the above Date constructor is:

Date (yr_num, mo_num, day_num, [, hr_num[, min_ num[, sec_num[, ms_num]]]])

The parameters hr_num (integer value for hours), min_num (integer value for minutes), sec_num (integer value for seconds), and ms_num (integer value for milliseconds) are optional.

UTC

UTC, a static method of the Date object, now supports milliseconds. It returns the number of milliseconds from midnight, January 1, 1970 UTC. The function calculates the time lapsed between January 1, 1970 UTC and the time you specified.

Syntax

Date.UTC(year, month, date, [, hours[, min[, sec[, ms]]]])

Parameters

year, month, and date (required parameters for an integer representing the year, month, and date)

hours, min, sec, and ms (optional parameters for an integer representing the hours, minutes, seconds, and milliseconds)

Description

You do not call this method as a method of the Date object you created. This method is a property of the Date constructor. It differs from the Date constructor in two ways. Date.UTC method uses Universal Coordinated Time (UTC) instead of the local time. Date.UTC also returns a time value as a number instead of creating a Date object. You do not need create a Date object before invoking Date.UTC method. You can invoke this static method directly.

You should specify a full year for the year, for example, 1998. If a year between 0 and 99 is specified, the method converts year to a year in the 20th century (1900 + year). In other words, if you specify 95, the year will be 1995. ms should be an integer value between 0 and 999. If a parameter you specify is outside of the expected range, the UTC method updates the other parameters to allow for your number. For example, if you use 15 for the month, the year will be updated by one (year + 1) and 3 will be used for month.

New Date Methods

There are three sets of new methods for the Date object. getFullYear and setFullYear are used for setting and getting the full year, for example, 1998. These methods should be used in place of getYear and setYear. Methods getMilliseconds and setMilliseconds are used for setting and getting the milliseconds of time. The rest of the methods are UTC specific. These methods are similar to the existing local time methods, except that they use the UTC time.

getFullYear

Syntax

getFullYear()

Parameters

None

Description

Returns the year of the specified date according to local time. The return value is an absolute number. For dates past the year between 1000 and 9999, it returns a four-digit number, for example, 1995. Use this function to make sure the year is compliant with years after 2000. To get the UTC date use getUTCFullYear. To set the full year use setFullYear. Use this method instead of the getYear method.

Example


var yr;

Today = new Date();

yr = Today.getFullYear();

setFullYear

Syntax

setFullYear(year [, month [, date]])

Parameters

year (a required parameter, specifying the numeric value of the year, for example, 1995)

month (an optional parameter, specifying the numeric value of the month, a number between 0 and 11)

date (an optional parameter, specifying the numeric value of the day of the month, a number between 1 and 31. You must specify month if you plan to use date)

Description

Sets the full year for a specified date according to local time. If you do not specify the month and date parameters, the values returned from getMonth and/or getDate methods are used. If a parameter you specify is outside of the expected range, setFullYear attempts to update the other parameters and/or the date information in the Date object, accordingly. For example, if you use 15 for the month, the year will be updated by one (year + 1) and 3 will be used for month. For UTC time, use getUTCFullYear. Use this method instead of the setYear method.

Example


theBigDay = new Date();

theBigDay.setFullYear(1997);

getMilliseconds

Syntax

getMilliseconds()

Parameters

None

Description

Returns the milliseconds in the specified date according to local time. The return value is a number between 0 and 999. If you want to get the milliseconds based on UTC, use the getUTCMilliseconds method, instead.

Example


var ms;

Today = new Date();

ms = Today.getMilliseconds();

setMilliseconds

Syntax

setMilliseconds()

Parameters

None

Description

Sets the milliseconds for a specified date according to local time. The number should be between 0 and 999. If you specify a number outside this range, the other stored date variables in the Date object are updated to accommodate your number. For example, if you specify 1005, the number of milliseconds will be 5 and the number of seconds in the date object is incremented by 1. For UTC time, use setUTCMilliseconds, instead.

Example


theBigDay = new Date();

theBigDay.setMilliseconds(100);

getUTCFullYear

Syntax

getUTCFullYear()

Parameter

None

Description

Returns the year according in the specified date to Universal Coordinated Time. The return value is an absolute number and compliant with year-2000, for example, 1995. For local time, use getFullYear, instead.

Example


var yr;

Today = new Date();

yr = Today.getUTCFullYear();

getUTCMonth

Syntax

getUTCMonth()

Parameter

None

Description

Returns the month according in the specified date according to Universal Coordinated Time. The value returned by getUTCMonth is an integer between 0 and 11. 0 corresponds to January, 1 to February, 3 to March, and so on. For local time, use getMonth, instead.

Example

var mon;

Today = new Date();

mon = Today.getUTCMonth();

getUTCDate

Syntax

getUTCDate()

Parameter

None

Description

Returns the day (date) of the month in the specified date according to Universal Coordinated Time. The value returned by getUTCDate is an integer between 1 and 31. For local time, use getDate, instead.

Example

var d;

Today = new Date();

d = Today.getUTCDate();

getUTCDay

Syntax

getUTCDay()

Parameter

None

Description

Returns the day of the week in the specified date according to Universal Coordinated Time. The value returned by getUTCDay is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. For local time, use getDay, instead.

Example


var weekday;

Today = new Date()

weekday = Today.getUTCDay()

getUTCHours

Syntax

getUTCHours()

Parameters

None

Description

Returns the hours in the specified date according to Universal Coordinated Time. The value returned by getUTCHours is an integer between 0 and 23. For local hours, use getHours, instead.

Example


var hrs;

Today = new Date();

hrs = Today.getUTCHours();

getUTCMinutes

Syntax

getUTCMinutes()

Parameters

None

Description

Returns the minutes in the specified date according to Universal Coordinated Time. The value returned by getUTCMinutes is an integer between 0 and 59. For local time, use getMinutes, instead.

Example


var min;

Today = new Date();

min = Today.getUTCMinutes();

getUTCSeconds

Syntax

getUTCSeconds()

Parameters

None

Description

Returns the seconds in the specified date according to Universal Coordinated Time. The value returned by getUTCSeconds is an integer between 0 and 59. For local hours, use getSeconds, instead.

Example


var sec;

Today = new Date();

sec = Today.getUTCSeconds();

getUTCMilliseconds

Syntax

getUTCMilliSeconds()

Parameters

None

Description

Returns the milliseconds in the specified date according to Universal Coordinated Time. The value returned by getUTCMilliseconds is an integer between 0 and 999.

Example


var ms;

Today = new Date();

ms = Today.getUTCMilliseconds();

toUTCString

Syntax

toUTCString()

Parameters

None

Description

Converts a date to a string, using Universal Coordinated Time convention. The result is a readable string formatted according toUTC convention. The exact format of the value returned may vary according to the platform. Although this method behaves in the same way as toGMTString, you should use toUTCString instead of toGMTString. toGMTSTring is now available for backward compatibility. For local time, use toString, instead.

Example


var UTCstring;

Today = new Date();

UTCstring = Today.getUTCString();

setUTCFullYear

Syntax

setUTCFullYear(year [, month[, date]])

Parameters

year (a required parameter, specifying the numeric value of the year, for example, 1995)

month (an optional parameter, specifying the numeric value of the month, a number between 0 and 11, where January is 0, February is 1, and so on)

date (an optional parameter, specifying the numeric value of the day of the month, a number between 1 and 31. You must specify month if you plan to use date)

Description

Sets the full year for a specified date according to Universal Coordinate Time. If you do not specify the month and date parameters, the values returned from getMonth and/or getDate methods are used. If a parameter you specify is outside of the expected range, setUTCFullYear attempts to update the other parameters and/or the date information in the Date object accordingly. For example, if you use 15 for the month, the year will be updated by one (year + 1) and 3 will be used for month. For local time, use getFullYear, instead.

Example


theBigDay = new Date();

theBigDay.setUTCFullYear(1997);

setUTCMonth

Syntax

setUTCMonth(month[, date])

Parameter

month (a required parameter, specifying the numeric value of the month, a number between 0 and 11, where January is 0, February is 1, and so on)

date (an optional parameter, specifying the numeric value of the day of the month, a number between 1 and 31)

Description

Sets the month for a specified date according to Universal Coordinate Time. If you do not specify the date parameter, the value returned from the getUTCDate method is used. If a parameter you specify is outside of the expected range, setUTCMonth attempts to update the date information in the Date object accordingly. For example, if you use 15 for the month, the year will be updated by one (year + 1) and 3 will be used for month. For local time, use getMonth, instead.

Example

theBigDay = new Date();

theBigDay.setUTCMonth(11);

setUTCDate

Syntax

setUTCDate(date)

Parameter

date (a required parameter, specifying the numeric value of the day of the month, a number between 1 and 31)

Description

Sets the day of the month for a specified date according to Universal Coordinate Time. If a parameter you specify is outside of the expected range, setUTCDate attempts to update the date information in the Date object accordingly. For example, if you use 40 for the date, and the month stored in the Date object is June, the date will be changed to 10 and the month will be incremented to July. For local time, use getDate, instead.

Example


theBigDay = new Date();

theBigDay.setUTCDate(20);

setUTCHours

Syntax

setUTCHour(hours[, min[, sec[,ms]]])

Parameter

hours (a required parameter, specifying the numeric value of the hour, an integer between 0 and 23.

min, sec, and ms (optional parameters, specifying the minutes, seconds, and milliseconds. You must specify min and sec, if you plan to use ms, and min if you plan to set ms)

Description

Sets the hour for a specified date according to Universal Coordinate Time. If you do not specify the min, sec, and ms parameters, the values returned from getUTCMinutes, getUTCSeconds, and getUTCMilliseconds methods are used. If a parameter you specify is outside of the expected range, setUTCHours attempts to update the date information in the Date object accordingly. For example, if you use 100 for sec, the minutes (min) will be updated by 1 (min + 1) and 40 will be used for seconds. For local time, use getHours, instead.

Example


theBigDay = new Date();

theBigDay.setUTCHour(8);

setUTCMinutes

Syntax

setUTCMinutes(min[, sec[, ms]])

Parameter

min (a required parameter, specifying the numeric value of the minutes, an integer between 0 and 59)

sec, and ms (optional parameters, specifying the seconds and milliseconds. You must specify sec if you plan to use ms)

Description

Sets the minutes for a specified date according to Universal Coordinate Time. If you do not specify the sec and ms parameters, the values returned from getUTCSeconds and getUTCMilliseconds methods are used. If a parameter you specify is outside of the expected range, setUTCMinutes attempts to update the date information in the Date object accordingly. For example, if you use 100 for sec, the minutes (min) will be updated by 1 (min + 1) and 40 will be used for seconds. For local time, use getMinutes, instead.

Example


theBigDay = new Date();

theBigDay.setUTCMinutes(43);

setUTCSeconds

Syntax

setUTCSeconds(sec [, ms])

Parameter

sec (a required parameter, specifying the numeric value of the seconds, an integer between 0 and 59)

ms (an optional parameters, specifying the milliseconds)

Description

Sets the seconds for a specified date according to Universal Coordinate Time. If you do not specify the ms parameter, the value returned from getUTCMilliseconds methods are used. If a parameter you specify is outside of the expected range, setUTCSeconds attempts to update the date information in the Date object accordingly. For example, if you use 100 for sec, the minutes stored in the Date object will be updated by 1 and 40 will be used for seconds. For local time, use getSeconds, instead.

Example


theBigDay = new Date();

theBigDay.setUTCSeconds(20);

setUTCMilliseconds

Syntax

setUTCMilliseconds(ms)

Parameter

ms (specifies the numeric value of the seconds, and integer between 0 and 999)

Description

Sets the milliseconds for a specified date according to Universal Coordinate Time. If a parameter you specify is outside of the expected range, setUTCMilliseconds attempts to update the date information in the Date object accordingly. For example, if you use 1000 for ms, the seconds stored in the Date object will be updated by 1 and 100 will be used for milliseconds. For local time, use getMilliseconds, instead.

Example


theBigDay = new Date();

theBigDay.setUTCMilliseconds(500);

Changes to the Date Methods

A number of Date methods supported in JavaScript 1.2 now take extra optional parameters. The following is a list of the JavaScript 1.3 Date methods and their parameters.

setMonth(month[, date])

setHours(hours[, min[, sec[, ms]]])

setMinutes(min[, sec[, ms]])

setSeconds(sec[, ms])

These methods perform similar to equivalent setUTC* methods, except that they set the date information according to local time. As with the setUTC* methods, if you do not specify these optional parameters, the appropriate get* methods are used, that is getDate, getMinute, getSeconds, and getMilliseconds. If the number specified for any of the parameter is outside of the range expected, the Date method attempts to update the date information in the Date object according. For example, if you use 100 for sec, the minutes stored in the Date object will be updated by 1 and 40 will be used for seconds.

New Methods of Function Object

JavaScript includes two new methods, call and apply, for the Function object. These new methods are proposed for the future ECMA specification. The method caller (included in JavaScript 1.2) is deprecated. It remains as a Function object method in JavaScript 1.3, for backward compatibility.

call

Syntax

call(thisArg, arg1, arg2, ...)

Parameters

thisArg (parameter for the calling object)

arg1, arg2, ... (an optional parameters of arguments for the object)

Description

call allows you to call (executes) a method of another object in the context of a different object (the calling object). You can assign a different this object when calling an existing function. this refers to the current object, the calling object. With call, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object. (See also the method apply.)

Example

You can use call to chain constructors for an object, similar to Java. In the following example, the constructor for object product is defined with two parameters, name and value. Another object prod_dept, after initializing its unique variable (dept) calls the constructor for product in its constructor to initialize the other variables.


function product(name, value){



    this.name = name;



    if(value > 1000)

       this.value = 999;

    else

       this.value = value;

}



function prod_dept(name, value, dept){



    this.dept = dept;



    product.call(this, name, value);

}



prod_dept.prototype = new product();



// since 5 is less than 100 value is set

cheese = new prod_dept("feta", 5, "food");  



// since 5000 is above 1000, value will be 999

car = new prod_dept("honda", 5000, "auto");

apply

Syntax

apply(thisArg, argArray)

Parameters

thisArg (parameter for the calling object)

argArray (an optional parameter of an argument array for the object)

Description

apply allows you to apply a method of another object in the context of a different object (the calling object). You can assign a different this object when calling an existing function. this refers to the current object, the calling object. With apply, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.

apply is very similar to call, except for the type of arguments it supports. You can use an arguments array instead of a named set of parameters. With apply, you can use an array literal, for example, apply(this, [name, value]), or an array object, for example, apply(this, new Array(name, value)). You can also use arguments for the argArray. arguments is a special property of the activation object. It can be used for all unspecified arguments of the called object. Thus, you do not have to know the arguments of the called object when you use the apply method. You can use arguments to pass all the arguments to the called object. The called object is then responsible for handling the arguments. If you want to have this flexibility, use apply with arguments parameter. (See also the method call.)

Example

You can use apply to chain constructors for an object, similar to Java. In the following example, the constructor for object product is defined with two parameters, name and value. Another object prod_dept, after initializing its unique variable (dept) calls the constructor for product in its constructor to initialize the other variables. In this example, the parameter arguments is used for all arguments of the product object's constructor.


function product(name, value){



    this.name = name;



    if(value > 1000)

       this.value = 999;

    else

       this.value = value;

}



function prod_dept(name, value, dept){



    this.dept = dept;

    product.apply(product, arguments);

}



prod_dept.prototype = new product();



// since 5 is less than 100 value is set

cheese = new prod_dept("feta", 5, "food");  



// since 5000 is above 1000, value will be 999

car = new prod_dept("honda", 5000, "auto");

Strict Equality Operators

Syntax

operand1 === operand2

operand1 !== operand2

Description

The strict equality operators (=== and !==) perform equality comparisons on operands of the same type. They only compare the identity of similarly typed operands. No type conversion is performed before the comparison is made. The type of the operands must be the same. For example, both operands must be of String type, before a comparison can be made.

In JavaScript 1.2, == and != operators (equality operators) performed this strict equality comparison. But, to comply with ECMA, in JavaScript 1.3, the equality operators have changed, and two new strict equality operators have been added. These new operators are not part of the current ECMA specification, but will be included in the next version.

Use strict operands if you want to make sure the two operands are of a specific type as well as value. For example, if you want to make sure the two operands are of the same type and value, use ===. If the type of operand does not matter but the value should be the same, use ==. For example, if you want to compare two operands independent of whether they are a number or a string then use the standard equality operator.

Strings are compared based on standard lexicographical ordering, using Unicode values. Two strings are equal when they have the exact same sequence of characters, same length, and same characters in corresponding positions. Two numbers are equal when they are numerically equal. In other words, they have the same number value. NaN is not equal to anything, including NaN. Positive and negative zeros are equal. Two objects are equal if they refer to the same Object. Boolean operands are the same if they are both true or false.

A Boolean value is returned as the result of the comparison. === returns true if the two operands are the same. !== returns true if the two operands are not equal. Otherwise, these operators return false. For example, 10 === '10' returns false, while 10 == '10' returns true.

Changes in JavaScript 1.3

The following changes to JavaScript 1.2 have been made in JavaScript 1.3. These features do not perform as they did in JavaScript 1.2. You must make the appropriate changes to your code in order for your code to be JavaScript 1.3-compliant.

Equality Operators

Syntax

operand1 == operand2

operand1 != operand2

Description

The use of equality operators in JavaScript 1.3 reverts to the JavaScript 1.1 implementation. If the type of the operands is different, JavaScript perform a type conversion before the equality comparison is made. Unlike with the strict equality operators, different type operands can be compared using the equality operator. A Boolean value is returned as the result of the comparison. For example, 10 === '10' returns true.

You should use strict equality operators, if the operands must be of a specific type as well as value or if the exact type of the operands is important. Otherwise, you should use the standard equality operators, which allows you to compare the identity of two operands even if they are not of the same type. You do not have to know if an operand is a string or a number before a comparison is made.

When operands are of the same type, the equality operator functions in the same way as a strict equality operator. Null and Undefined types are equal. Any comparison of an operand, including NaN, with NaN returns false. Positive and negative zeros are equal.

If the two operands are of type String, Number, Boolean, or Object, but they are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison. When comparing a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value. If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false. If an Object is compared with a number or string, JavaScript attempts to return the default value for the Object. Operators attempt to convert the Object to a primitive value, a String or Number value, using the valueOf and toString methods of the Objects. If this attempt to convert the Object fails, a runtime error is generated.

Array

In this section, the changes to the Array object for JavaScript 1.3 are discussed.

Length property

The length of an array (property length) is now an unsigned, 32-bit integer. The value of the length property is an integer with a positive sign and a value less than 2 to the 32 power.

Constructor

The Array constructor in JavaScript 1.2 returned a single-element array when you specified a single parameter. In other words, new Array(5), when you specify LANGUAGE="JavaScript1.2", creates a new array with the first element being 5, a[0]=5. Although ArrayLength was documented as a unique parameter for a single parameter (argument) constructor in JavaScript 1.2, a constructor with a single parameter acted in the same way as a multiple parameter constructor. You could not specify the length property of an Array using a constructor with one parameter. This use of the single-parameter constructor is different from JavaScript 1.3, which now acts similarly to JavaScript 1.1.

In JavaScript 1.3, when you use a single-parameter constructor, the constructor verifies if the argument is a number. If it is a number, the constructor converts the number to an unsigned, 32-bit integer and generates an array with the length property (size of the array) set to the integer. The initial value of the elements of the Array will be undefined.

Push Method

In JavaScript 1.2, the push method returned the last element added to an array. Under JavaScript 1.3, push returns the new length of the array.

Splice Method

In JavaScript 1.2, the splice method returned the element removed, if only one element was removed (howMany parameter is 1). In JavaScript 1.3, splice always returns an array containing the removed elements. If one element is removed, an array of one element is returned.

replace Method of String Object

Syntax: replace(regexp, newSubStr)

In JavaScript 1.3, the replace method of the String object supports the nesting of a function in place of the second argument (the use of a function in this manner is often called a lambda expression).

Optional Syntax: replace(regexp, function)

When you specify a function as the second parameter, your function will be invoked after the match (String method match) has been performed. In your function, you can dynamically generate the string that will replace the matched substring. The result of the function call will be used as the replacement value.

The nested function can use the matched substrings to determine the new string (newSubStr) that will replace the found substring. You get the matched substrings through the parameters of your function. The first parameter of your function will hold the complete matched substring. Other parameters can be used for parenthetical matches, remembered submatch strings. For example, the following replace method:


"XXzzzz".replace(/(X*)(z*)/, 

                   function (str, p1, p2) { 

                     return str + " - " + p1 + " , " + p2; 

                   }

                )  

returns XX.zzzz - XX , zzzz.

The array returned from the RegExp method exec and the subsequent match, is available to your function. You can use the content of the array plus the input and the index (index of match in the input string) properties of the array to perform any additional task before the method replaces the substring.

Example

The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.

The regular expression test checks for any number that ends with F. The number of Fahrenheit degree is accessible to your function through the parameter $1. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the f2c function. f2c then returns the Celsius number. This function approximates Perl's s///e flag.


function f2c(x) {

   var s = String(x)

   var test = /(\d+(\.\d*)?)F\b/g



   return s.replace

                (test,

                  myfunction ($0,$1,$2) { 

                     return (($1-32) * 5/9) + "C";

                  }

                )

}

Boolean Object

In JavaScript 1.2, a Boolean false object was treated as false in conditional tests. When a Boolean object was used as the condition in an if statement (if(condition)), JavaScript 1.2 returned the value of the Boolean object. If the Boolean object was a false object, the statement was evaluated to false. In JavaScript 1.3, the if statement only verifies if the condition is really a Boolean object and returns true, if it is. All objects are considered true in a conditional test, including the Boolean false object.

In the following example, the if statement is evaluated to true.


x = new Boolean(false);



if(x)

{

    /* run my code */

}

As a rule, it is always best to delineate exactly what type of condition you wish JavaScript to evaluate. For instance, if you want to identify if a variable is not null, you should use if(x != null), instead of if(x).

toString

In JavaScript 1.2 (when you specify LANGUAGE="JavaScript1.2"), the toString method of the Object and Array objects returned an object or array literal string, respectively. (See section JavaScript Terms, below, for a description of object literal and array literal.)

In JavaScript 1.3, the toString method of an Object returns [object type], where type is the name of the object type or the name of the constructor function that created the object. For example, when using the toString method of an Image Object named SeaLion ( SeaLion.toString()), the method returns [object Image]. The toString method of Array returns a string containing each array elements separated by commas. The elements of the Array object are converted to strings, which are concatenated and separated by commas. (See also toSource above.)

Supplements to JavaScript Manual

This section is a supplement to the existing JavaScript documentation. It describes JavaScript concepts not part of the existing JavaScript documentation.

Reserved Keywords

You should not use JavaScript statements keywords and the special operator keywords as identifier in your program. This will lead to a run-time error, when the script is loaded. JavaScript Keywords are: break, comment, continue, delete, do, while, export, for, in, function, if, else, import, label, return, switch, var, while, and with. The special operator words are: new, this, typeof, and void.

The following keywords are added to the list of JavaScript reserved words. These words are reserved for future versions of JavaScript. With the exception of debugger, they are also part of the Java keywords. By not using them as identifiers, you make sure your JavaScript code can work with Java.

JavaScript Terms

Although earlier versions of JavaScript support the following concepts, these terms were not documented in the JavaScript Reference Guide.

Array Literal

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]).

The following is an example of array literal. The element of an array literal can include a string (home), a number (3), a variable (work), a function that returns an element (newElement(14)), and a nested array (['school', 10]). The index of the elements begins with zero (0), but the length of array (for example, myList.length) reflects the number of elements in the array.


var work = "Netscape";



function newElement(name) {



if(isNaN(name))

    return name + " is a wrong type of element";

else

    return name;

}



myList = ['home', 3, work, newElement(14), ['school', 10]];



document.write(myList[0]);             // home

document.write(myList[1]);             // 3

document.write(myList[2]);             // party

document.write(myList[3]);             // 14

document.write(myList[4][0]);          // school

document.write(myList[4][1]);          // 1

document.write(myList.length);         // 5

You can have an empty element inside the list of the elements in an array literal.


myList = ['home', , 'school']; 

In the above array, the length of myList is 3, and A[1] is missing.

If you include a trailing comma at the end of the list of elements, the comma will be ignored. As with C and Java, JavaScript does not interpret this final trailing comma as an indicator for a new element. In the following example, the length of array is still 3. There is no A[3].


myList = ['home', , 'school', ];

All other commas in the list indicate a new element.

In the next example, the length of array is 4 and myList[0] is also missing.


myList = [ , 'home', , 'school'];

In the following example, the length of array is still 4 and myList[3] is missing.


myList = ['home', , 'school', , ];

Only the last comma is ignored. This trailing comma is optional.

Object Literal

An object literal is a list of zero or more pairs of property names and associated value of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error.

The following is an example of an object literal. The first element of the Object car defines a property (myCar); the second element, property getCar, invokes a function (Cars("honda")); the third element, property special, uses an existing variable (Sales).


var Sales = "Toyota";



function CarTypes(name) {



if(name == "Honda")

    return name;

else

    return "Sorry, we don't sell " + name + ".";

}



car = {myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales}



document.write(car.myCar);     // Saturn

document.write(car.getCar);    // Honda

document.write(car.special);   // Toyota

Additionally, you can use an index for the object, property index (for example, 7), or nest an object inside another. The following example uses these options. These features, however, may not be supported by other ECMA-compliant browsers.


car = {manyCars: {a: "Saab", b: "Jeep"}, 7: "Mazda"}



document.write(car.manyCars.b);   // Jeep

document.write(car[7]);           // Mazda

Primitive Value

Primitive values are data, which are directly represented at the lowest level of the language. A primitive value is a member of one of the following types: undefined, null, boolean, number, or string.

JavaScript Console

Netscape Navigator and Communicator 4.06 and 4.5 support a "console" similar to the Java console. This console is a single window that will display all JavaScript error messages. In the future, the console may also support non-JavaScript messages and warnings.

When a JavaScript error condition is encountered in the client (for example, on an HTML page or within an email message), a dialog window pops up describing the error (for example, Line 64: myVariable is not defined). For most users, these errors are incomprehensible and dismissing the dialog windows becomes annoying. Only JavaScript developers, testers, and very sophisticated users are likely to be interested in looking at these JavaScript errors.

With Navigator/Communicator 4.06 and 4.5, you can force these errors to display only in the JavaScript console. In other words, when a JavaScript error occurs, no dialog box will appear. Instead, the error message is directed to the JavaScript console. Since the console is normally not displayed, there will be no direct indication that a JavaScript error has occurred for the user. If a user or developer would like to verify the JavaScript error, they only need to open the console.

You can set a preference in the browser preference file to automatically open the console when a JavaScript error occurs. You can even set a preference to use the old Navigator behavior of opening the dialog boxes when a JavaScript error occurs.

The text of JavaScript error message appears the same way whether they are displayed in the JavaScript console or in the traditional error dialogs. Currently, JavaScript error descriptions are always displayed in English regardless of the locale. They are not 118N-friendly. Localized JavaScript error-handling will be supported in future releases of the Communicator/Navigator.

Currently, the only way you can open the console window is by entering the special URL, javascript:, in the location bar, as you would any other URL. For now, unlike Java Console, you cannot open the JavaScript console from the browser menu. This menu option will be added in future releases of the Communicator/Navigator.

Setting the JavaScript Console Preferences

The following instructions are for the JavaScript console. Set these preferences in the Navigator preference file. You will find the preference file in the specific userís directory under the Netscape/Users directory. For example, under NT, you may find the preference file, prefs.js, under <Netscape path>\Users\<user name>. Make sure Navigator is not running when you edit your preferences or it may overwrite your customization.

Automating the Opening of the JavaScript Console

To have the JavaScript console automatically open when a JavaScript error occurs, add the following line to your preferences file.

user_pref("javascript.console.open_on_error", true);

Now, when a JavaScript error occurs, the console window will automatically open and scroll down to the new error message.

Enabling the JavaScript Error Dialog Box

If you prefer to have the error dialog box open when an error occurs, you can add the following line to your preference file.

user_pref("javascript.classic.error_alerts", true);

Additional Notes

You should take special note of the following issues when writing your JavaScript code.

eval

You should not indirectly use the function eval. This option may not be supported in the future versions of JavaScript and is not a valid ECMA call. For example, you should not use the following code:


var x = 2;

var y = 4;



var myEval = eval;

myEval("x + y");

You may still call eval directly. For example, you can use eval("x + y"). eval will then evaluate the expression.

Using Assignment in a Conditional Statement

You should not use simple assignments in a conditional statement. For instance, do not use the following code:


if(x = y)

{

    /* do the right thing */

}

Earlier versions of JavaScript convert the assignment operator to an equality operator. In other words, if(x = y) is converted to if(x == y). The Navigator also displayed an alert dialog box with the following message: test for equality (==) mistyped as assignment (=)? Assuming equality test.

For Navigator 4.06 and later, if you need to use an assignment in a conditional statement, you should put another parenthesis around the assignment. For example, you should use if( (x = y) ).

toLocaleString Method of Date Object

The toLocaleString method relies on the underlying operating system in formatting dates. It converts the date to a string using the formatting convention of the operating system, where the script is running. For example, in the United States, the month appears before the date (04/15/98), where as in Germany the date appears before the month (15.04.98). If the operating system is not year-2000 compliant and does not use the full year for years before 1900 or over 2000, then toLocaleString will return a string that is not year-2000 compliant. toLocaleString behaves similar to toString when converting a year that the operating system does not properly format.

caller Property of the Function Object

The caller function may be deprecated in future versions of JavaScript. You should avoid using this function.

escape and unescape

escape and unescape support the JavaScript 1.2 behavior. They do not use Unicode as specified in ECMA.

These methods are most commonly used for encoding and decoding a Uniform Resource Locator (URL), a Uniform Resource Identifier (URI), or a URI-type string. URI specification set forth by the Internet Engineering Task Force (IETF), however, does not use Unicode. Within a URI, characters use US-ASCII characters (ISO-Latin-1 character set). A URI is a sequence of characters from basic Latin alphabet, digits, and a few special characters (for example, / and @). URI uses escaped octet encoding, hexadecimal encoding. The escape sequences do not support \uXXXX as in Unicode or %uXXXX as specified by ECMA, but %XX, where XX is a 2-digit hexadecimal number (for example, %7e). In URI, characters are represented in octets, as 8-bit bytes.

To allow escape and unescape methods to work with Web server-supported URLs and URIs, JavaScript 1.3 does not use Unicode for these methods. unescape returns the ASCII string, an ISO-Latin-1 character set sequence. escape returns the hexadecimal encoding of the specified string in the ISO-Latin-1 character set. Unicode specific escape sequences, %uXXXX, are not supported.

OB

For the latest technical information on Sun-Netscape Alliance products, go to: http://developer.iplanet.com

For more Internet development resources, try Netscape TechSearch.


Copyright © 1999 Netscape Communications Corporation.
This site powered by: Netscape Enterprise Server and Netscape Compass Server.