JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

5.10. Miscellaneous Operators

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

5.10.1. 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 be (or be convertable to) 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, the value of the conditional expression is the value of the second operand. If the first operand is false, the value of the conditional expression is the value of the third operand.

While you can achieve similar results using the if statement, the ?: operator often provides a handy shortcut. 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 " + (username != null ? username : "there"); 

This is equivalent to, but more compact than, the following if statement:

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

5.10.2. The typeof Operator

typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.

The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value. It evaluates to "object" for objects, arrays, and (surprisingly) null. It evaluates to "function" for function operands and to "undefined" if the operand is undefined.

typeof evaluates to "object" when its operand is a Number, String, or Boolean wrapper object. It also evaluates to "object" for Date and RegExp objects. typeof evaluates to an implementation-dependent value for objects that are not part of core JavaScript but are provided by the context in which JavaScript is embedded. In client-side JavaScript, however, typeof typically evaluates to "object" for all client-side objects, just as it does for all core objects.

You might use the typeof operator in expressions like these:

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

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

typeof(i) 

Because typeof evaluates to "object" for all object and array types, it is useful only to distinguish objects from other, primitive types. In order to distinguish one object type from another, you must use other techniques, such as the instanceof operator or the constructor property (see the "Object.constructor" entry in the core reference section).

The typeof operator is defined by the ECMAScript v1 specification and is implemented in JavaScript 1.1 and later.

5.10.3. The Object Creation Operator (new)

The new operator creates a new object and invokes a constructor function to initialize it. new is a unary operator that appears before a constructor invocation. It has the following syntax:

new constructor(arguments) 

constructor must be an expression that evaluates to a constructor function, and it should be followed by zero or more comma-separated arguments enclosed in parentheses. As a special case, for the new operator only, JavaScript simplifies the grammar by allowing the parentheses to be omitted if there are no arguments in the function call. Here are some examples using the new operator:

o = new Object;    // Optional parentheses omitted here
d = new Date( );  // Returns a Date object representing the current time
c = new Rectangle(3.0, 4.0, 1.5, 2.75);  // Create an object of class Rectangle
obj[i] = new constructors[i]( ); 

The new operator first creates a new object with no properties defined; next, it invokes the specified constructor function, passing the specified arguments and also 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 new operator, the this keyword, and constructor functions in Chapter 8.

The new operator can also be used to create arrays, using the new Array( ) syntax. We'll see more about creating and working with objects and arrays in Chapter 8 and Chapter 9.

5.10.4. The delete Operator

delete is a unary operator that attempts to delete the object property, array element, or variable specified as its operand.[17] It returns true if the deletion was successful, and false if the operand could not be deleted. Not all variables and properties can be deleted: some built-in core and client-side properties are immune from deletion, and user-defined variables declared with the var statement cannot be deleted. If delete is invoked on a nonexistent property, it returns true. (Surprisingly, the ECMAScript standard specifies that delete also evaluates to true if the operand is not a property, array element, or variable.) Here are some examples of the use of this operator:

[17]If you are a C++ programmer, note that the delete operator in JavaScript is nothing like the delete operator in C++. In JavaScript, memory deallocation is handled automatically by garbage collection, and you never have to worry about explicitly freeing up memory. Thus, there is no need for a C++-style delete to delete entire objects.

var o = {x:1, y:2};  // Define a variable; initialize it to an object
delete o.x;          // Delete one of the object properties; returns true
typeof o.x;          // Property does not exist; returns "undefined"
delete o.x;          // Delete a nonexistent property; returns true
delete o;            // Can't delete a declared variable; returns false
delete 1;            // Can't delete an integer; returns true
x = 1;               // Implicitly declare a variable without var keyword
delete x;            // Can delete this kind of variable; returns true
x;                   // Runtime error: x is not defined

Note that a deleted property, variable, or array element is not merely set to the undefined value. When a property is deleted, the property ceases to exist. See the related discussion in Section 4.3.2.

delete is standardized by the ECMAScript v1 specification and implemented in JavaScript 1.2 and later. Note that the delete operator exists in JavaScript 1.0 and 1.1 but does not actually perform deletion in those versions of the language. Instead, it merely sets the specified property, variable, or array element to null.

It is important to understand that delete affects only properties, not objects referred to by those properties. Consider the following code:

var my = new Object( );    // Create an object named "my"
my.hire = new Date( );     // my.hire refers to a Date object
my.fire = my.hire;          // my.fire refers to the same object
delete my.hire;             // hire property is deleted; returns true
document.write(my.fire);    // But my.fire still refers to the Date object 

5.10.5. The void Operator

void is a unary operator that appears before its single operand, which may be of any type. The purpose of this operator is an unusual one: it discards its operand value and returns undefined. The most common use for this operator is in a client-side javascript: URL, where it allows you to evaluate an expression for its side effects without the browser displaying the value of the evaluated expression.

For example, you might use the void operator in an HTML tag as follows:

<a href="javascript:void window.open( );">Open New Window</a> 

Another use for void is to purposely generate the undefined value. void is specified by ECMAScript v1 and implemented in JavaScript 1.1. The global undefined property, however, is specified by ECMAScript v3 and implemented in JavaScript 1.5. Thus, for backward compatibility, you may find it useful to use an expression like void 0 instead of relying on the undefined property.

5.10.6. 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, the following line:

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

evaluates to 2, and is basically equivalent to:

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

This strange operator is useful only in a few limited circumstances, primarily when 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 really used only in conjunction with the for loop statement, which we'll see in Chapter 6.

5.10.7. Array and Object Access Operators

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

The . operator expects an object as its left operand and an identifier (a property name) as its right operand. The right operand should not be a string or a variable that contains a string; it should be the literal name of the property or method, 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 undefined 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 righthand operand must be an identifier. Nothing else is allowed.

The [] operator allows access to array elements. It also allows access to object properties without the restrictions that the . operator places on the righthand operand. If the first operand (which goes before the left bracket) refers to an array, the second operand (which goes between the brackets) should be an 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, the second operand should be an 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 an identifier. It should be a constant in quotes or a variable or expression that refers to a string. For example:

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

The [] operator is typically 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, the . operator cannot be used; only the [] operator will do. This is commonly the case when you use the for/in loop, which is introduced in Chapter 6. For example, the following JavaScript code uses a for/in loop and the [] operator to print out the names and values of all of the properties in an object o:

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

5.10.8. The 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. It 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 then invokes the function specified by the first operand, with the values of the remaining operands passed as arguments. For example:

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


Library Navigation Links

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