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


JavaScript: The Definitive Guide

Previous Chapter 4
Expressions and Operators
Next
 

4.9 Miscellaneous Operators

JavaScript supports a number of other miscellaneous operators, described in the sections below.

The Conditional Operator (?:)

The conditional operator is the only ternary operator (three operands) in JavaScript and is sometimes actually called the ternary operator. This operator is sometimes written ?:, although it does not appear quite that way in code. Because this operator has three operands, the first goes before the ?, the second goes between the ? and the :, and the third goes after the :. It is used like this:

x > 0 ? x*y : -x*y

The first operand of the conditional operator must have a Boolean value--usually this is the result of a comparison expression. The second and third operands may have any value. The value returned by the conditional operator depends on the Boolean value of the first operand. If that operand is true, then the value of the conditional expression is the value of the second operand. If the first operand is false, then the value is the value of the third operand.

While you can achieve similar results using the if statement, the ?: operator is a very handy shortcut in many cases. Here is a typical usage, which checks to be sure that a variable is defined, uses it if so, and provides a default value if not.

greeting = "hello " + ((name != null) ? name : "there");
This is equivalent to, but more compact than, the following if statement:

greeting = "hello ";
if (name != null) 
    greeting += name;
else 
    greeting += "there";

The typeof Operator

The typeof operator is available in Navigator 3.0 and Internet Explorer 3.0. typeof is an unusual operator because it is not represented by punctuation characters but instead by the typeof keyword. It is a unary operator that is placed before its single operand, which can be of any type. The value of the typeof operator is a string indicating the data type of the operand.[3]

[3] This means that typeof typeof x, where x is any value, will always yield the value "string".

Possible values are "number", "string", "boolean", "object", "function", and "undefined" for undefined values. Both arrays and objects return the "object" value. typeof may be used as follows:

typeof i
(typeof value == "string") ? "'" + value + "'" : value

Note that you can place parentheses around the operand to typeof, which will make typeof look like the name of a function rather than an operator keyword:

typeof(i)

Object Creation Operator (new)

As we saw earlier, numbers, strings, and Boolean values are represented through textual literals in JavaScript. That is, you just type their string representation into your program, and then your program can manipulate that value. As we'll see later, you can use the function keyword to define functions that your program can work with. But JavaScript supports two other data types as well--objects and arrays. Object and array values cannot simply be typed into your JavaScript programs; they must be created. The new operator is used to do this.

The new operator is one, like typeof, that is represented by a keyword rather than by special punctuation characters. This is a unary operator that appears before its operand. It has the following syntax:

new constructor
constructor must be a function-call expression (i.e., it must include an expression that refers to a function, and this function should be followed by an optional argument list in parentheses). As a special case, for this new operator only, JavaScript simplifies the grammar by allowing the parentheses to be omitted if there are no arguments in the function call. Example uses of the new operator are:

o = new Object;   // optional parentheses omitted here
d = new Date();
c = new rectangle(3.0, 4.0, 1.5, 2.75);
obj[i] = new constructors[i]();

The new operator works as follows: first, it creates a new object with no properties defined. Next, it invokes the specified constructor function, passing the specified arguments, and passing the newly created object as the value of the this keyword. The constructor function can then use the this keyword to initialize the new object in any way desired. We'll learn more about the this keyword and about constructor functions in Chapter 7, Objects.

In Navigator 3.0, you create a JavaScript array with the new Array() syntax. In Navigator 2.0, there is not an Array() constructor function defined. In this version of JavaScript, you can create an array with the Object() constructor instead. Some scripts will define their own custom Array() constructor.

We'll see more about creating and working with objects and arrays in Chapter 7, Objects and Chapter 8, Arrays.

The delete Operator

If you are a C++ programmer, then you probably expect JavaScript to have a delete operator that destroys objects created with the new operator. JavaScript does have such an operator, but it does not behave in the same way the C++ delete. In Navigator 2.0 and 3.0, delete simply sets its operand (a variable, object property, or array element) to null. You could obviously do this with an assignment statement just as easily, and in fact, delete is deprecated in Navigator 2.0 and 3.0; you should not use it at all. This mostly-useless version of the operator was created in a beta version of Navigator 2.0, and never quite got removed from the language. In Navigator 4.0, however, there is a new, non-deprecated, delete operator which is more functional--it actually deletes, or undefines a variable or object property.

Note that even this new Navigator 4.0 delete operator is not the same as the C++ delete--it simply undefines a variable or property, and does not actually delete or destroy or free up the memory associated with an object created with new. The reason that a C++-style delete is not necessary is that JavaScript provides automatic "garbage collection"--when objects and other values are no longer being used, the memory associated with them is automatically reclaimed by the system. You don't have to worry about deleting objects or freeing or releasing memory that is no longer in use. Garbage collection in JavaScript is discussed in more detail in Chapter 11, Windows and the JavaScript Name Space.

The void Operator

The void operator is supported in Navigator 3.0, but not in Internet Explorer 3.0. IE will support it in a future version.

void is a unary operator that appears before an expression with any value. The purpose of this operator is an unusual one: it always discards its operand value and simply returns an undefined value. The only occasion on which you are likely to want to do this is in a javascript: URL, in which you want to evaluate an expression for its side effects, but do not want the browser to display the value of the evaluated expression. Thus, you might use the void operator in HTML like the following:

<A HREF="javascript:void document.form1.submit();">Submit Form</A>

The Comma Operator (,)

The comma operator is a simple one. It evaluates its left argument, evaluates its right argument, and then returns the value of its right argument. Thus, this line:

i=0, j=1, k=2;
is equivalent to:

i = 0;
j = 1;
k = 2;

This strange operator is useful only in a few limited circumstances in which you need to evaluate several independent expressions with side effects in a situation where only a single expression is allowed. In practice, the comma operator is only frequently used in conjunction with the for loop statement, which we'll see later in Chapter 5, Statements.

Array and Object Access Operators

As noted briefly in Chapter 3, Variables and Data Types, you can access elements of an array using square brackets [], and you can access elements of an object using a dot (.); both of these are treated as operators in JavaScript.

The . operator expects an object as its left operand, and the name of an object property or method as the right operand. This right operand should not be a string or a variable that contains a string, but should be the literal name of the property, without quotes of any kind. Here are some examples:

document.lastModified
navigator.appName
frames[0].length
document.write("hello world")

If the specified property does not exist in the object, JavaScript does not issue an error, but instead simply returns the special undefined value as the value of the expression.

Most operators allow arbitrary expressions for either operand, as long as the type of the operand is suitable. The . operator is an exception: the right-hand operand must be a literal property name. Nothing else is allowed.

The [] operator allows access to array elements and also to object properties, and it does so without the restrictions that the . operator places on the right-hand operand. If the first operand (which goes before the left bracket) refers to an array, then the second operand (which goes between the brackets) can be an arbitrary expression that evaluates to an integer. For example:

frames[1]
document.forms[i + j]
document.forms[i].elements[j++]

If the first operand to the [] operator is a reference to an object, on the other hand, then the second operand may be an arbitrary expression that evaluates to a string that names a property of the object. Note that in this case, the second operand is a string, not a literal name. It should be a constant in quotes, or a variable or expression that refers to a string. This works like associative arrays in the Perl and awk programming languages. For example:

document["lastModified"]
frames[0]['length']
data["val" + i]

The [] operator is usually used to access the elements of an array. It is less convenient than the . operator for accessing properties of an object because of the need to quote the name of the property. When an object is used as an associative array, however, and the property names are dynamically generated, then the . operator cannot be used, and only the [] operator will do. This is commonly the case when you use the for/in loop, which will be introduced in Chapter 5, Statements. For example, the following JavaScript code uses a for/in loop and the [] operator to print out the name and value of all properties f in an object o:

for (f in o) {
    document.write('o.' + f + ' = ' + o[f]);
    document.write('<BR>');
}

Function Call Operator

The () operator is used to invoke functions in JavaScript. This is an unusual operator in that it does not have a fixed number of operands. The first operand is always the name of a function or an expression that refers to a function. This is followed by the left parenthesis and any number of additional operands, which may be arbitrary expressions, each separated from the next with a comma. The right parenthesis follows the final operand. The () operator evaluates each of its operands, and invokes the function specified by the first, with the value of the remaining operands passed as arguments. Examples:

document.close()
Math.sin(x)
alert("Welcome " + name)
Date.UTC(99, 11, 31, 23, 59, 59)
funcs[i].f(funcs[i].args[0], funcs[i].args[1])


Previous Home Next
Assignment Operators Book Index Statements

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell