home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeWebmaster in a Nutshell, 3rd EditionSearch this book

11.2. Syntax

JavaScript syntax is modeled on Java syntax; Java syntax, in turn, is modeled on C and C++ syntax. Therefore, C, C++, and Java programmers should find that JavaScript syntax is comfortably familiar.

11.2.8. Data Types

JavaScript supports three primitive data types: numbers, booleans, and strings; and two compound data types: object and arrays. In addition, it defines specialized types of objects that represent functions, regular expressions, and dates.

11.2.8.3. Strings

A JavaScript string is a sequence of arbitrary letters, digits, and other characters from the 16-bit Unicode character set.

String literals appear in JavaScript programs between single or double quotes. One style of quotes may be nested within the other:

'testing'
"3.14"
'name="myform"'
"Wouldn't you prefer O'Reilly's book?"

When the backslash character (\) appears within a string literal, it changes, or escapes, the meaning of the character that follows it. The following table lists these special escape sequences:

Escape

Represents

\b

Backspace

\f

Form feed

\n

Newline

\r

Carriage return

\t

Tab

\'

Apostrophe or single quote that does not terminate the string

\"

Double-quote that does not terminate the string

\

Single backslash character

\xdd

Character with Latin-1 encoding specified by two hexadecimal digits dd

\udddd

Character with Unicode encoding specified by four hexadecimal digits dddd

The String class defines many methods that you can use to operate on strings. It also defines the length property, which specifies the number of characters in a string.

The addition (+) operator concatenates strings. The equality (==) operator compares two strings to see if they contain exactly the same sequences of characters. (This is compare-by-value, not compare-by-reference, as C, C++, or Java programmers might expect.) The inequality operator (!=) does the reverse. The relational operators(<, <=, >, and >=) compare strings using alphabetical order.

JavaScript strings are immutable, which means that there is no way to change the contents of a string. Methods that operate on strings typically return a modified copy of the string.

11.2.9. Expressions and Operators

JavaScript expressions are formed by combining values (which may be literals, variables, object properties, array elements, or function invocations) using JavaScript operators. Parentheses can be used in an expression to group subexpressions and alter the default order of evaluation of the expression. Some examples:

1+2
total/n
sum(o.x, a[3])++

JavaScript defines a complete set of operators, most of which should be familiar to C, C++, and Java programmers. They are listed in the table below, and a brief explanation of the nonstandard operators follows. The P column specifies operator precedence and the A column specifies operator associativity: L means left-to-right associativity, and R means right-to-left associativity.

P

A

Operator

Operation performed

15

L

.

Access an object property

 

L

[ ]

Access an array element

 

L

( )

Invoke a function

 

R

new

Create new object

14

R

++

Pre-or-post increment (unary)

 

R

--

Pre-or-post decrement (unary)

 

R

-

Unary minus (negation)

 

R

+

Unary plus (no-op)

 

R

~

Bitwise complement (unary)

 

R

!

Logical complement (unary)

 

R

delete

Undefine a property (unary) (JS 1.2)

 

R

typeof

Return data type (unary) (JS 1.1)

 

R

void

Return undefined value (unary) (JS 1.1)

13

L

*, /, %

Multiplication, division, remainder

12

L

+, -

Add, subtract

 

L

+

Concatenate strings

11

L

<<

Integer shift left

 

L

>>

Shift right, sign-extension

 

L

>>>

Shift right, zero extension

10

L

<, <=

Less than, less than or equal

 

L

>, >=

Greater than, greater than or equal

 

L

instanceof

Check object type (JS 1.5)

 

L

in

Check whether property exists (JS 1.5)

9

L

==

Test for equality

 

L

!=

Test for inequality

 

L

===

Test for identity (JS 1.3)

 

L

!==

Test for non-identity (JS 1.3)

8

L

&

Integer bitwise AND

7

L

^

Integer bitwise XOR

6

L

|

Integer bitwise OR

5

L

&&

Logical AND

4

L

||

Logical OR

3

R

?:

Conditional operator (3 operands)

2

R

=

Assignment

 

R

*=, +=, -=, etc.

Assignment with operation

1

L

,

Multiple evaluation

JavaScript operators that are not familiar from C, C++, and Java are the following:

=== and !==
The JavaScript equality operator, ==, defines equality loosely and allows type conversions. For example, it considers the number 3 and the string "3" to be equal, it considers false to be equal to 0, and it considers null and undefined to be equal. The identity operator, ===, written with three equals signs, is stricter: it only evaluates to true if its operands are identical: i.e., if they have the same type and are equal. Similarly, the JavaScript non-identity operator !== is stricter than the non-equality != operator.

String operators
In JavaScript, the + operator concatenates string arguments in addition to adding numeric arguments. The == and === operators compare strings by value by testing to see whether they contain exactly the same characters. The relational operators <, <=, >, and >= compare strings based on alphabetical order.

typeof
Return the type of the operand as a string. Evaluates to "number", "string", "boolean", "object", "function", or "undefined". Evaluates to "object" if the operand is null.

instanceof
Evaluates to true if the object on the left was created with the constructor function (such as Date or RegExp) on the right.

in
Evaluates to true if the object on the right has (or inherits) a property with the name on the left.

delete
Deletes an object property. Note that this is not the same as simply setting the property to null. Evaluates to false if the property could not be deleted, or true otherwise.

void
Ignores the operand and evaluates to undefined.

11.2.10. Statements

A JavaScript program is a sequence of JavaScript statements. Most JavaScript statements have the same syntax as the corresponding C, C++, and Java statements.

11.2.10.5. Alphabetical statement reference

The following paragraphs document all JavaScript statements, in alphabetical order.

break
The break statement terminates execution of the innermost enclosing loop, or, in JavaScript 1.2 and later, the named loop:

break ;
break label ;
case
case is not a true statement. Instead it is a keyword used to label statements within a JavaScript 1.2 or later switch statement:

case constant-expression :
    statements
    [ break ; ]

Because of the nature of the switch statement, a group of statements labeled by case should usually end with a break statement.

continue
The continue statement restarts the innermost enclosing loop, or, in JavaScript 1.2 and later, restarts the named loop:

continue ;
continue label ;
default
Like case, default is not a true statement, but instead a label that may appear within a JavaScript 1.2 or later switch statement:

default:
    statements
    [ break ; ]
do/while
The do/while loop repeatedly executes a statement while an expression is true. It is like the while loop, except that the loop condition appears (and is tested) at the bottom of the loop. This means that the body of the loop is executed at least once:

do
    statement
while ( expression ) ;

This statement was introduced in JavaScript 1.2. In Netscape 4, the continue statement does not work correctly within do/while loops.

for
The for statement is an easy-to-use loop that combines the initialization and increment expressions with the loop condition expression:

for (initialize ; test ; update )
    statement

The for loop repeatedly executes statement as long as the test expression is true. It evaluates the initialize expression once before starting the loop and evaluates the update expression at the end of each iteration.

for/in
The for/in statement loops through the properties of a specified object:

for (variable in object)
    statement

The for/in loop executes a statement once for each property of an object. Each time through the loop, it assigns the name of the current property to the specified variable. Some properties of pre-defined JavaScript objects are not enumerated by the for/in loop. User-defined properties are always enumerated.

function
The function statement defines a function in a JavaScript program:

function funcname ( args ) {
    statements
}

This statement defines a function named funcname, with a body that consists of the specified statement, and arguments as specified by args. args is a comma-separated list of zero or more argument names. These arguments can be used in the body of the function to refer to the parameter values passed to the function.

if/else
The if statement executes a statement if an expression is true:

if ( expression )
    statement

When an else clause is added, the statement executes a different statement if the expression is false:

if ( expression )
    statement
else
    statement2

Any else clause may be combined with a nested if/else statement to produce an else if statement:

if ( expression )
    statement
else if ( expression2 )
    statement2
else
    statement3
return
The return statement causes the currently executing function to stop executing and return to its caller. If followed by an expression, the value of that expression is used as the function return value:

return ;
return expression ;
switch
The switch statement is a multi-way branch. It evaluates an expression and then jumps to a statement that is labeled with a case clause that matches the value of the expression. If no matching case label is found, the switch statement jumps to the statement, if any, labeled with default:

switch ( expression ) {
    case constant-expression: statements
    [ case constant-expression: statements ]
    [  . . .  ]
    default: statements
}

Each set of statements within a switch statement is usually terminated with a break or return so that execution does not fall through from one case to the next one.

throw
The throw statement signals an error, or throws an exception. It causes program control to jump immediately to the nearest enclosing exception handler (see the try/catch/finally statement). The throw statement is defined by ECMAv3 and implemented in JavaScript 1.5. Its syntax is:

throw expression ;

The expression may evaluate to any type. (See Error in the reference section.)

try/catch/finally
The try/catch/finally statement is JavaScript's exception handling mechanism. It is defined by ECMAv3 and implemented in JavaScript 1.5. Its syntax is:

try {
    statements
}
catch ( argument ) {
    statements
}
finally {
    statements
}

The try clause of this statement defines a block of code for which exceptions and errors are to be handled. If a program error occurs, or an exception is thrown within the try block, control jumps to the exception-handling statements in the catch clause. This clause includes a single argument or local variable; the value that was thrown by the exception is assigned to this local variable so that it can be referred to by the statements of the catch clause. The finally clause contains statements that are executed after the try or catch clauses, whether or not an exception is thrown. The catch and finally clauses are optional, but you cannot omit both of them.

var
The var statement declares and optionally initializes one or more variables. Variable declaration is optional in top-level code, but is required to declare local variables within function bodies:

var name [ = value ] [ , name2 [ = value2 ]  . . .  ] ;
while
The while statement is a basic loop. It repeatedly executes a statement while an expression is true:

while ( expression )
    statement ;
with
The with statement adds an object to the scope chain, so that a statement is interpreted in the context of the object:

with ( object )
    statement ;

The with statement has some complex and nonintuitive side effects; its use is strongly discouraged.

11.2.11. Object-Oriented JavaScript

JavaScript objects are associative arrays that associate values with named properties. JavaScript provides a simple inheritance mechanism, and it is possible to define new classes of objects for use in your own programs. To define a new class, start by writing a constructor function. A constructor is like any other function, except it is invoked with the new operator and it uses the this keyword to refer to and initialize the newly created object. For example, here is a constructor to create objects of a new class named Point.

function Point(x,y) { // Constructor for Point
  this.x = x;  // Initialize X coordinate
  this.y = y;  // Initialize Y coordinate
}

Every JavaScript function used as a constructor has a property named prototype. This property refers to a special prototype object for the class of objects created by the constructor. Any properties you define on this prototype object are inherited by all objects created with the constructor function. The prototype object is commonly used to make methods available to all instances of a class. Defining a method named toString allows instances of your class to be converted to strings. For example:

// Define function literals and assign them 
// to properties of the prototype object.
Point.prototype.distanceTo = function(that) {
  var dx = this.x - that.x;
  var dy = this.y - that.y;
  return Math.sqrt(dx*dx + dy*dy);
}
Point.prototype.toString = function () {
  return '(' + this.x + ',' + this.y + ')';
}

If you want to define static (or class) methods or properties, you can assign them directly to the constructor function, rather than to the prototype object. For example:

// Define a commonly used Point constant
Point.ORIGIN = new Point(0,0);

The preceding code fragments define a simple Point class that we can use with code like this:

// Call constructor to create a new Point object
var p = new Point(3,4);
// Invoke a method of the object, using a static
// property as the argument.  
var d = p.distanceTo(Point.ORIGIN);
// Adding the object to a string implicitly
// invokes toString().
var msg = "Distance to " + p + " is " + d;

11.2.12. Regular Expressions

JavaScript supports regular expressions for pattern matching with the same syntax as the Perl programming language. JavaScript 1.2 supports Perl 4 regular expressions, and JavaScript 1.5 adds supports for some of the additional features of Perl 5 regular expressions. A regular expression is specified literally in a JavaScript program as a sequence of characters within slash (/) characters, optionally followed by one or more of the modifier characters g (global search), i (case-insensitive search), and m (multi-line mode; a JavaScript 1.5 feature). In addition to this literal syntax, RegExp objects can be created with the RegExp( ) constructor, which accepts the pattern and modifier characters as string arguments, without the slash characters.

A full explanation of regular expression syntax is beyond the scope of this chapter, but the tables in the following subsections offer brief syntax summaries.

11.2.13. Versions of JavaScript

Netscape has defined numerous versions of JavaScript. Microsoft has released more-or-less compatible versions under the name "JScript," and the ECMA standards body has released three versions of a JavaScript standard named "ECMAScript". The following paragraphs describe these various versions, and explain how they relate to each other. Each entry in the reference section contains availability information that documents the version of JavaScript in which a feature was introduced.

JavaScript 1.0
The original version of the language. It was buggy and is now essentially obsolete. Implemented by Netscape 2.

JavaScript 1.1
Introduced a true Array object; most serious bugs resolved. Implemented by Netscape 3.

JavaScript 1.2
Introduced the switch statement, regular expressions, and a number of other features. Almost compliant with ECMA v1, but has some incompatibilities. Implemented by Netscape 4.

JavaScript 1.3
Fixed incompatibilities of JavaScript 1.2. Compliant with ECMA v1. Implemented by Netscape 4.5.

JavaScript 1.4
Only implemented in Netscape server products.

JavaScript 1.5
Introduced exception handling. Compliant with ECMA v3. Implemented by Mozilla and Netscape 6.

JScript 1.0
Roughly equivalent to JavaScript 1.0. Implemented by early releases of IE 3.

JScript 2.0
Roughly equivalent to JavaScript 1.1. Implemented by later releases of IE 3.

JScript 3.0
Roughly equivalent to JavaScript 1.3. Compliant with ECMA v1. Implemented by IE 4.

JScript 4.0
Not implemented by any web browser.

JScript 5.0
Supported exception handling; partial ECMA v3 compliance. Implemented by IE 5.

JScript 5.5
Roughly equivalent to JavaScript 1.5. Fully compliant with ECMA v3. Implemented by IE 5.5 and IE 6.

ECMA v1
The first standard version of the language. Standardized the basic features of JavaScript 1.1 and added a few new features. Did not standardize the switch statement or regular expression support. Conformant implementations are JavaScript 1.3 and JScript 3.0.

ECMA v2
A maintenance release of the standard that included clarifications but defined no new features.

ECMA v3
Standardized the switch statement, regular expressions, and exception handling. Conformant implementations are JavaScript 1.5 and JScript 5.5.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.