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


Dynamic HTML: The Definitive Reference, 2rd Ed.Dynamic HTML: The Definitive ReferenceSearch this book

12.6. Operators

 
+NN 2 IE 3 ECMA 1

The addition operator works with both numbers and strings, but its results vary with the data types of its operands. When both operands are numbers, the result is the sum of the two numbers; when both operands are strings, the result is a concatenation of the two strings (in the order of the operands); when one operand is a number and the other a string, the number data type is converted to a string, and the two strings are concatenated. To convert a string operand to a number, use the parseInt( ) or parseFloat( ) function.

Example

var mySum = number1 + number2;
var newString = "string1" + "string2";
 
 
&&NN 2 IE 3 ECMA 1

The AND operator compares two Boolean expressions for equality. If both expressions evaluate to true, the result of the && operator also evaluates to true; if either or both expressions are false, the && operator evaluates to false.

A Boolean expression may consist of a comparison expression (using any of the many comparison operators) or a variety of other values. Here are the most common data types, values, and their Boolean value equivalent.

Data type

Boolean equivalent

Number other than zero

true

Zero

false

Any nonempty string

true

Empty string

false

Any object

true

null

false

undefined

false
Using this information, you can create compound conditions with the help of the && operator. For example, if you want to see if someone entered a value into a form field and it is a number greater than 100, the condition would look like the following:

var userEntry = document.forms[0].entry.value ;
if (userEntry && parseInt(userEntry) >= 100) {
    ...
}

If the user had not entered any value, the string would be an empty string. In the compound condition, when the first operand evaluates to false, the && operator rules mean that the entire expression returns false (because both operands must be true for the operator to return true). Because evaluation of expressions such as the compound condition are evaluated from left to right, the false value of the first operand short-circuits the condition to return false, meaning that the second operand isn't evaluated.

Example

if (a <= b && b >= c) {
    ...
}
 
=NN 2 IE 3 ECMA 1

The assignment operator assigns the evaluated value of the right-hand operand to the variable on the left. After the operation, the variable contains data of the same data type as the original value. Assignment operations can also be chained, with the evaluation of the entire statement starting from the right and working left. Therefore, after the expression:

a = b = c = 25;

all three variables equal 25.

Example

var myName = "Theodore Roosevelt";
var now = new Date( );
 
&NN 2 IE 3 ECMA 1

The bitwise AND operator performs binary math on two operands (their binary values). Each column of bits is subjected to the Boolean AND operation. If the value of a column in both operands is 1, the result for that column position is 1. All other combinations yield a zero. The resulting value of the operator is the decimal equivalent of the binary result. For example, the binary values of 3 and 6 are 0011 and 0110, respectively. After an AND operation on these two values, the binary result is 0010; the decimal equivalent is 2.

Example

var n = 3 & 6;
 
<<NN 2 IE 3 ECMA 1

The bitwise left-shift operator shifts the bits of the first operand by the number of columns specified by the second operand. For example, if the binary value of 3 (0011) has its bits shifted to the left by 2, the binary result is 1100; the decimal equivalent is 12.

Example

var shifted = 3 << 2;
 
~NN 2 IE 3 ECMA 1

This is the bitwise NOT operator. This unary operator inverts the value of the binary digit in each column of a number. For example, the binary 6 is 0110 (with many more zeros off to the left). After the negation operation on each column's value, the binary result is 1001, plus all zeros to the left inverted to 1s. The decimal equivalent is a negative value (-5).

Example

var n = ~6;
 
|NN 2 IE 3 ECMA 1

The bitwise OR operator performs binary math on two operands (their binary values). Each column of bits is subjected to the Boolean OR operation. If the value of a column in both operands is 0, the result for that column position is 0. All other combinations yield a 1. The resulting value of the operator is the decimal equivalent of the binary result. For example, the binary values of 3 and 6 are 0011 and 0110, respectively. After an OR operation on these two values, the binary result is 0111; the decimal equivalent is 7.

Example

var n = 3 | 6;
 
>>NN 2 IE 3 ECMA 1

The bitwise right-shift operator shifts the bits of the first operand by the number of columns specified by the second operand. For example, if the binary value of 6 (0110) has its bits shifted to the right by 2, the binary result is 0001; the decimal equivalent is 1. Any digits that fall off the right end of the number are discarded.

Example

var shifted = 6 >> 2;
 
^NN 2 IE 3 ECMA 1

The bitwise exclusive OR (XOR) operator performs binary math on two operands (their binary values). Each column of bits is subjected to the Boolean XOR operation. If the value of a column in either operand (but not both operands) is 1, the result for that column position is 1. All other combinations yield a 0. The resulting value of the operator is the decimal equivalent of the binary result. For example, the binary values of 3 and 6 are 0011 and 0110, respectively. After an XOR operation on these two values, the binary result is 0101; the decimal equivalent is 5.

Example

var n = 3 ^ 6;
 
>>>NN 2 IE 3 ECMA 1

This is the bitwise zero-fill right-shift operator. This operator shifts the bits of the first operand (to the right) by the number of columns specified by the second operand. With the bitwise right-shift operator (>>), new digits that fill in from the left end are 1s; with the zero-fill right-shift operator (>>>), the new digits at the left are zeros. Any digits that fall off the right end of the number are discarded. Microsoft also refers to this operator as the unsigned right-shift operator.

Example

var shifted = 6 >>> 2;
 
,NN 2 IE 3 ECMA 1

The comma operator (with or without optional white space following it) can delimit expressions in the same line of script. It can be used in a number of ways. For example, to declare multiple variables, the syntax would be:

var varName1, varName2, ... varNameN;

Multiple script statements may also be joined together on the same line. Therefore, the following script line:

alert("Howdy"), alert("Doody");

presents two alert dialog boxes in sequence (the second one appears after the first is dismissed by the user). Another application is in for loops when you wish to involve two (or more) variables in the loop:

for (var i = 0, var j = 2; i < 20; i++, j++) {
    ...
}

Example

var isCSS, isIEMac;
 
?:NN 2 IE 3 ECMA 1

The conditional operator provides a shortcut syntax to an if/else control structure. There are three components to the deployment of this operator: a condition and two statements. If the condition evaluates to true, the first of the statements is executed; if the condition evaluates to false, the second statement is evaluated. The syntax is as follows:

condition ? statement1 : statement2

You can nest these operators as a way of adding more decision paths within a single statement. In the following syntax, if conditionA evaluates to false, conditionB is evaluated, and the entire expression returns the value of statement2 or statement3 depending on the results of conditionB.

conditionA ? statement1 : (conditionB ? statement2 : statement3)

This operator is a shortcut in appearance only. It invokes the same internal processing as an if...else construction.

Example

var newColor = (temp > 100) ? "red" : "blue";
 
NN 2 IE 3 ECMA 1

The decrement operator (a unary operator) subtracts 1 from the current value of a variable expression. You can place the operator in front of or behind the variable for a different effect. When the operator is in front of the variable, the variable is decremented before it is evaluated in the current statement. For example, in the following sequence:

var a, b;
a = 5;
b = --a;

one is subtracted from a before being assigned to b. Therefore, both b and a are 4 when these statements finish running. In contrast, in the following sequence:

var a, b;
a = 5;
b = a--;

the subtraction occurs after a is assigned to b. When the statements complete, b is 5 and a is 4.

This behavior impacts the way for-loop-counting variables are defined and used. Typically, a loop counter that counts backwards from a maximum value decrements the counter after the statements in the loop have run. Thus most loop counters place the operator after the counter variable:

for (var i = 10; i >=0; i--) {...}

Example

--n
n--
 
/NN 2 IE 3 ECMA 1

The division operator divides the number to the left of the operator by the number to the right. Both operands must be numbers. An expression with this operator evaluates to a number.

Example

var myQuotient = number1 / number2;
 
==NN 2 IE 3 ECMA 1

The equality operator compares two operand values and returns a Boolean result. The behavior of this operator differs with the version of JavaScript specified for the script element. If the language attribute is set to JavaScript or JavaScript1.1, some operands are automatically converted as shown in the following table.

Left operand

Right operand

Description

Object reference

Object reference

Compare evaluation of object references.

Any data type

Boolean

Convert Boolean operand to a number (1 for true; 0 for false) and compare against other operand.

Object reference

String

Convert object to string (via toString( )) and compare strings.

String

Number

Convert string to a number and compare numeric values.

Navigator 4 and later observes slightly different value conversions for determining equality when you explicitly set the script element to language="JavaScript1.2". The browser is more literal about equality, meaning that no automatic data conversions are performed. Therefore, whereas the expression:

123 == "123"

evaluates to true in most situations due to automatic data type conversion, the expression evaluates to false in Navigator 4 and later but only in statements belonging to explicitly JavaScript 1.2 scripts. Because newer DOM and XHTML standards don't provide a place to specify scripting language versions, you should avoid these special-case situations. If your scripts require tests for absolute equality of operands, use the newer === identity operator instead. For typical value equality testing, the standard equality operators work perfectly well.

Regardless of version, if you wish to compare the values of objects (for example, comparing strings explicitly generated with the new String( ) constructor), you should compare the values derived from methods such as toString( ) or valueOf( ).

Example

if (n == m) {
    ...
}
 
>NN 2 IE 3 ECMA 1

The greater-than operator compares the values of operands on either side of the operator. If the numeric value of the left operand is larger than the right operand, the expression evaluates to true. Strings are converted to their Unicode values for comparison of those values.

Example

if (a > b) {
    ...
}
 
>=NN 2 IE 3 ECMA 1

The greater-than-or-equal operator compares the values of operands on either side of the operator. If the numeric value of the left operand is larger than or equal to the right operand, the expression evaluates to true. Strings are converted to their Unicode values for comparison of those numeric values.

Example

if (a >= b) {
    ...
}
 
===NN 4 IE 4 ECMA 2

The strictly equals (identity) operator compares two operand values and returns a Boolean result. Both the value and data type of the two operands must be identical for this operator to return true (no automatic data type conversions occur). See the equality operator (==) for more liberal equality comparisons.

Example

if (n === m) {
    ...
}
 
++NN 2 IE 3 ECMA 1

The increment operator (a unary operator) adds 1 to the current value of a variable expression. You can place the operator in front of or behind the variable for a different effect. When the operator is in front of the variable, the variable is incremented before it is evaluated in the current statement. For example, in the following sequence:

var a, b;
a = 5;
b = ++a;

1 is added to a before being assigned to b. Therefore, both b and a are 6 when these statements finish running. In contrast, in the following sequence:

var a, b;
a = 5;
b = a--;

the addition occurs after a is assigned to b. When these statements complete, b is 5 and a is 6.

This behavior impacts the way for-loop-counting variables are defined and used. Typically, a loop counter that counts upward from a minimum value increments the counter after the statements in the loop have run. Thus, most loop counters place the operator after the counter variable:

for (var i = 10; i >=0; i++) {...}

Example

++n
n++
 
!=NN 2 IE 3 ECMA 1

The inequality operator compares two operand values and returns a Boolean result. The behavior of this operator differs with the version of JavaScript specified for the script element. If the language attribute is set to JavaScript or JavaScript1.1, some operands are automatically converted as for the equality (==) operator. The situation is a bit different in Navigator 4 or later when the script element is set to language="JavaScript1.2". The browser is more literal about inequality, meaning that no automatic data conversions are performed. Therefore, whereas the expression:

123 != "123"

evaluates to false in most situations due to automatic data type conversion, the expression evaluates to true in Navigator 4 and later in statements belonging to explicitly JavaScript 1.2 scripts. Because newer DOM and XHTML standards don't provide a place to specify scripting language versions, you should avoid these special-case situations. If your scripts require tests for absolute inequality of operands, use the newer !== identity operator instead. For typical value inequality testing, the standard inequality operators work perfectly well.

Regardless of version, if you wish to compare the values of objects (for example, strings explicitly generated with the new String( ) constructor), you should compare the values derived from methods such as toString( ) or valueOf( ).

Example

if (n != m) {
    ...
}
 
<NN 2 IE 3 ECMA 1

The less-than operator compares the values of operands on either side of the operator. If the numeric value of the left operand is smaller than the right operand, the expression evaluates to true. Strings are converted to their Unicode values for comparison of those values.

Example

if (a < b) {
    ...
}
 
<=NN 2 IE 3 ECMA 1

The less-than-or-equal operator compares the values of operands on either side of the operator. If the numeric value of the left operand is smaller than or equal to the right operand, the expression evaluates to true. Strings are converted to their Unicode values for comparison of those numeric values.

Example

if (a <= b) {
    ...
}
 
%NN 2 IE 3 ECMA 1

The modulus operator divides the number to the left of the operator by the number to the right. If a remainder exists after the division, the expression evaluates to that remainder as an integer. If there is no remainder, the returned value is zero. Both operands must be numbers. An expression with this operator evaluates to a number. Even if you aren't interested in the remainder value, this operator is a quick way to find out if two values are evenly divisible.

Example

if ((dayCount % 7) > 0) {
    ...
}
 
*NN 2 IE 3 ECMA 1

The multiplication operator multiplies the number to the left of the operator by the number to the right. Both operands must be numbers. An expression with this operator evaluates to a number.

Example

var myProduct = number1 * number2;
 
-NN 2 IE 3 ECMA 1

This is the negation operator. This unary operator negates the value of the single operand. For example, in the following statements:

a = 5;
b = -a;

the value of b becomes -5. A negation operator applied to a negative value returns a positive value.

Example

var myOpposite = -me;
 
!==NN 4 IE 4 ECMA n/a

The strict-not-equals (nonidentity) operator compares two operand values and returns a Boolean result. Both the value and data type of the two operands must be identical for this operator to return false. For less stringent comparisons, see the inequality operator (!=).

Example

if (n !== m) {
    ...
}
 
!NN 2 IE 3 ECMA 1

This is the NOT operator. This unary operator evaluates to the negative value of a single Boolean operand. The NOT operator should be used with explicit Boolean values, such as the result of a comparison or a Boolean property setting.

Example

if (a == !b) {
    ...
}
 
||NN 2 IE 3 ECMA 1

The OR operator compares two Boolean expressions for equality. If either or both expressions evaluate to true, the result of the || operator also evaluates to true; if both expressions are false, the || operator evaluates to false. A Boolean expression may consist of a comparison expression (using any of the many comparison operators) or a variety of other values. See the discussion of the AND operator for a summary of the most common data types, values, and their Boolean value equivalent.

You can create compound conditions with the help of the || operator. For example, if you want to see if either or both of two conditions are true, you would create a condition such as the following:

var userEntry1 = document.forms[0].entry1.value;
var userEntry2 = document.forms[0].entry2.value;
if (userEntry1 || userEntry2) {
    ...
}

In the compound condition, the || operator wants to know if either or both operands is true before it evaluates to true. If the user entered text into the first field, the condition short-circuits because a true value of either operand yields a true result. If text were entered only in the second field, the second operand is evaluated. Because it evaluates to true (a nonempty string), the condition evaluates to true. Only when both operands evaluate to false does the compound condition evaluate to false.

Example

if (a <= b || b >= c) {
    ...
}
 
-NN 2 IE 3 ECMA 1

The subtraction operator subtracts the number to the right of the operator from the number on the left. Both operands must be numbers. An expression with this operator evaluates to a number.

Example

var myDifference = number1 - number2;
 
deleteNN 4 IE 4 ECMA 1

The delete operator removes a property from an object (e.g., a prototype property from an instance of an object to whose static object your script added the prototype earlier) or an item from a script-generated array. Removing an array entry does not alter the array's length or the numerical indexes of existing items. Instead, the value of the deleted item is simply undefined. The delete operator is not a memory management tool.

Example

delete myString.author;
 
inNN 6 IE 5.5(Win) ECMA n/a

The in operator lets scripts quickly uncover whether an object has a particular property or method implemented for it. The left operand is a string containing the name of the property or method (method name without parentheses), while the right operand is a reference to the object. If your exploration requires DOM references entailing "dots," put them in the object reference side of the expression. In other words, instead of trying "style.filter" in document.body, use "filter" in document.body.style. Were it not that so few browsers implement this future ECMA operator, it would be a useful tool in object detection.

Example

if ("createDocument" in document.implementation) {
    // go ahead and use document.implementation.createDocument( )
}
 
instanceofNN 6 IE 5(Win) ECMA n/a

The instanceof operator lets scripts determine if an object (the left operand) is an instance of a known object (or inherited from the known object). In some ways, this operator is like the typeof operator, but rather than returning a broad object type, an expression with the instanceof operator returns a Boolean value against your test for a more specific object type. In fact, you can query an object against custom objects and, in Netscape 6, W3C DOM tree object prototypes. Whereas the typeof operator on an array returns object, you can find out if an object was instantiated specifically as an array:

myVar instanceof Array

Note, however, that if the above expression evaluates to true, so does:

myVar instanceof Object

An array is a descendant of the root Object object, and is thus an instance of that root object, as well.

In Netscape 6, either or both operands can also be references to DOM prototype objects. Therefore, the following expression is legal and operational in Netscape 6:

document.getElementById("widget") instanceof HTMLDivElement 

Example

if (theVal instanceof Array) {
    // go ahead and treat theVal as an array
}
 
newNN 2 IE 3 ECMA 1

The new operator creates instances of the following ECMA standard static objects:

Array

Boolean

Date

Function

Number

Object

RegExp

String

An expression with this operator evaluates to an instance of the object. In other words, invoking this operator makes JavaScript look for a constructor function with the same name. Thus, the new operator also works with custom objects that are formed via custom constructor functions. It also works in IE for Windows for creating instances of proprietary objects, such as ActiveX and VBArray objects.

Syntax rules allow naming the static object, the static object with empty parentheses, and the static object with parameters in parentheses:

var myArray = new Array;
var myArray = new Array( );
var myArray = new Array("Larry", "Moe", "Curly");

Only the last two examples are guaranteed to work in all scriptable browser versions. With the exception of the Date object, if you omit assigning parameters during the native object creation, the newly minted instance has only the properties that are assigned to the prototype of the static object.

Example

var now = new Date( );
 
thisNN 2 IE 3 ECMA 1

Refers to the current object. For example, in a form control object event handler, you can pass the object as a parameter to the function:

<input type="text" name="ZIP" onchange="validate(this);">

Inside a custom object constructor, the keyword refers to the object itself, allowing you to assign values to its properties (even creating the properties at the same time):

function CD(label, num, artist) {
    this.label = label;
    this.num = num;
    this.artist = artist;
}

Inside a function, the this keyword refers to the function object. However, if the function is assigned as a method of a custom object constructor, this refers to the instance of the object in whose context the function executes.

Example

<input type="text" name="phone" onchange="validate(this.value);">
 
typeofNN 3 IE 3 ECMA 1

The typeof operator returns one of six string descriptions of the data type of a value. Those returned types are:

boolean

function

number

object

string

undefined

The object type includes arrays, but the operator provides no further information about the type of object or array of the value (see the instanceof operator).

Example

if (typeof someVar == "string") {
    ...
}
 
voidNN 3 IE 4 ECMA 1

This unary operator evaluates the expression to its right but returns a value of undefined, even if the expression (such as a function call) evaluates to some value. This operator is commonly used with javascript: pseudo-URLs that invoke functions. If the function returns a value, that value is ignored by the calling expression.

Example

<a href="javascript: void getSound( );" >...</a>


Library Navigation Links

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