+ | NN 2 IE 3 ECMA 1 |
var mySum = number1 + number2; var newString = "string1" + "string2";
+= | NN 2 IE 3 ECMA 1 |
a += " and some more.";
Without the add-by-value operator, the operation had to be structured as follows:
a = a + " and some more";
The following table shows all the assignment operators that function this way.
Operator |
Example |
Equivalent |
---|---|---|
+= | a += b | a = a + b |
-= | a -= b | a = a - b |
*= | a *= b | a = a * b |
/= | a /= b | a = a / b |
%= | a %= b | a = a % b |
<<= | a <<= b | a = a << b |
>>= | a >>= b | a = a >> b |
>>>= | a >>>= b | a = a >>> b |
&= | a &= b | a = a & b |
|= | a |= b | a = a | b |
^= | a ^= b | a = a ^ b |
output += "<H1>Section 2</H1>"; total *= .95;
&& | NN 2 IE 3 ECMA 1 |
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 |
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.
if (a <= b && b >= c) { ... }
= | NN 2 IE 3 ECMA 1 |
a = b = c = 25;
all three variables equal 25.
var myName = "Theodore Roosevelt"; var now = new Date( );
& | NN 2 IE 3 ECMA 1 |
var n = 3 & 6;
<< | NN 2 IE 3 ECMA 1 |
var shifted = 3 << 2;
~ | NN 2 IE 3 ECMA 1 |
var n = ~6;
| | NN 2 IE 3 ECMA 1 |
var n = 3 | 6;
>> | NN 2 IE 3 ECMA 1 |
var shifted = 6 >> 2;
^ | NN 2 IE 3 ECMA 1 |
var n = 3 ^ 6;
>>> | NN 2 IE 3 ECMA 1 |
var shifted = 6 >>> 2;
, | NN 2 IE 3 ECMA 1 |
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++) { ... }
var isCSS, isIEMac;
?: | NN 2 IE 3 ECMA 1 |
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.
var newColor = (temp > 100) ? "red" : "blue";
— | NN 2 IE 3 ECMA 1 |
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--) {...}
--n n--
/ | NN 2 IE 3 ECMA 1 |
var myQuotient = number1 / number2;
== | NN 2 IE 3 ECMA 1 |
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( ).
if (n == m) { ... }
> | NN 2 IE 3 ECMA 1 |
if (a > b) { ... }
>= | NN 2 IE 3 ECMA 1 |
if (a >= b) { ... }
=== | NN 4 IE 4 ECMA 2 |
if (n === m) { ... }
++ | NN 2 IE 3 ECMA 1 |
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++) {...}
++n n++
!= | NN 2 IE 3 ECMA 1 |
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( ).
if (n != m) { ... }
< | NN 2 IE 3 ECMA 1 |
if (a < b) { ... }
<= | NN 2 IE 3 ECMA 1 |
if (a <= b) { ... }
% | NN 2 IE 3 ECMA 1 |
if ((dayCount % 7) > 0) { ... }
* | NN 2 IE 3 ECMA 1 |
var myProduct = number1 * number2;
- | NN 2 IE 3 ECMA 1 |
a = 5; b = -a;
the value of b becomes -5. A negation operator applied to a negative value returns a positive value.
var myOpposite = -me;
!== | NN 4 IE 4 ECMA n/a |
if (n !== m) { ... }
! | NN 2 IE 3 ECMA 1 |
if (a == !b) { ... }
|| | NN 2 IE 3 ECMA 1 |
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.
if (a <= b || b >= c) { ... }
- | NN 2 IE 3 ECMA 1 |
var myDifference = number1 - number2;
delete | NN 4 IE 4 ECMA 1 |
delete myString.author;
in | NN 6 IE 5.5(Win) ECMA n/a |
if ("createDocument" in document.implementation) { // go ahead and use document.implementation.createDocument( ) }
instanceof | NN 6 IE 5(Win) ECMA n/a |
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
if (theVal instanceof Array) { // go ahead and treat theVal as an array }
new | NN 2 IE 3 ECMA 1 |
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.
var now = new Date( );
this | NN 2 IE 3 ECMA 1 |
<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.
<input type="text" name="phone" onchange="validate(this.value);">
typeof | NN 3 IE 3 ECMA 1 |
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).
if (typeof someVar == "string") { ... }
void | NN 3 IE 4 ECMA 1 |
<a href="javascript: void getSound( );" >...</a>
Copyright © 2003 O'Reilly & Associates. All rights reserved.