= | 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: |
|
Multiple script statements may also be joined together on the same line. Therefore, the following script line: |
|
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 |
|
|
These are comment statements that let you enter nonexecuting text in a script. Any text following the // symbol anywhere in a statement line is ignored by the language interpreter. The next line of script, unless it begins with another // symbol, is interpreted by the browser. |
|
For multiline comment blocks, you can begin a block with the /* symbol. Comment blocks may run any number of lines. The block is closed with the */ symbol, after which the interpreter engages subsequent statements. |
|
Example | |
// convert temp from C to F /* many lines of comments */ |
//, /*...*/ | NN 2 IE 3 ECMA 1 |
|
|
These are comment statements that let you enter nonexecuting text in a script. Any text following the // symbol anywhere in a statement line is ignored by the language interpreter. The next line of script, unless it begins with another // symbol, is interpreted by the browser. |
|
For multiline comment blocks, you can begin a block with the /* symbol. Comment blocks may run any number of lines. The block is closed with the */ symbol, after which the interpreter engages subsequent statements. |
|
Example | |
// convert temp from C to F /* many lines of comments */ |
@cc_on, @if, @end, @set | NN n/a IE 4(Win) ECMA n/a |
|
|
IE for Windows includes a scripting feature called conditional compilation. It is a mode that, once turned on via the @cc_on statement, allows JScript statements to run under conditions that are testable within this conditional environment. If you surround conditional compilation statements by JavaScript comments, the conditional statements run only in IE 4 or later for Windows, while not conflicting with other browsers. |
|
The "conditional" part comes from numerous global properties (all preceded with the @ symbol) that reveal environmental properties, such as script engine version, operating system, and CPU type. All of this information is available from the navigator object's properties on a wide range of browsers, so this is not unique information available only to this conditional environment. |
|
To engage conditional compilation, include the following statement in your script: /*@cc_on @*/ |
|
This is a one-way toggle: once the mode is turned on, it can't be turned off in the current page. |
|
The following fragment shows how the @if and related statements display some environmental information in the window's status bar if the browser is running JScript Version 5.6 or later (IE 6 or later): /*@cc_on @*/ /*@if (@_jscript_version>= 5.6 && @_x86) status = "Now running JScript version " + @_jscript_version + " with Intel inside."; @else @*/ status = "Have a nice day."; /*@end @*/ |
|
The @set statement lets you assign a numeric or Boolean value (no strings) to a variable (a variable with an @ prefix) within a conditional compilation section: @set @isOK = @_win32 |
|
Once initialized, that variable (including its otherwise unacceptable identifier) can be used in script statements throughout the page. Note that the Visual Basic-inspired syntax of @ statements in conditional compilation statements does not permit semicolons at the end of statements. |
|
On the one hand, conditional compilation could be useful for IE-only deployment to screening older IE versions from new language features that would generate compilation errors (such as try-catch constructions) because such statements compile only under very controllable version situations. In a multibrand browser development shop, however, at most you might find application for IE-only debugging purposes, but probably not for actual application deployment. |
|
Example | |
See the discussion above. |
@cc_on, @if, @end, @set | NN n/a IE 4(Win) ECMA n/a |
|
|
IE for Windows includes a scripting feature called conditional compilation. It is a mode that, once turned on via the @cc_on statement, allows JScript statements to run under conditions that are testable within this conditional environment. If you surround conditional compilation statements by JavaScript comments, the conditional statements run only in IE 4 or later for Windows, while not conflicting with other browsers. |
|
The "conditional" part comes from numerous global properties (all preceded with the @ symbol) that reveal environmental properties, such as script engine version, operating system, and CPU type. All of this information is available from the navigator object's properties on a wide range of browsers, so this is not unique information available only to this conditional environment. |
|
To engage conditional compilation, include the following statement in your script: /*@cc_on @*/ |
|
This is a one-way toggle: once the mode is turned on, it can't be turned off in the current page. |
|
The following fragment shows how the @if and related statements display some environmental information in the window's status bar if the browser is running JScript Version 5.6 or later (IE 6 or later): /*@cc_on @*/ /*@if (@_jscript_version>= 5.6 && @_x86) status = "Now running JScript version " + @_jscript_version + " with Intel inside."; @else @*/ status = "Have a nice day."; /*@end @*/ |
|
The @set statement lets you assign a numeric or Boolean value (no strings) to a variable (a variable with an @ prefix) within a conditional compilation section: @set @isOK = @_win32 |
|
Once initialized, that variable (including its otherwise unacceptable identifier) can be used in script statements throughout the page. Note that the Visual Basic-inspired syntax of @ statements in conditional compilation statements does not permit semicolons at the end of statements. |
|
On the one hand, conditional compilation could be useful for IE-only deployment to screening older IE versions from new language features that would generate compilation errors (such as try-catch constructions) because such statements compile only under very controllable version situations. In a multibrand browser development shop, however, at most you might find application for IE-only debugging purposes, but probably not for actual application deployment. |
|
Example | |
See the discussion above. |
@cc_on, @if, @end, @set | NN n/a IE 4(Win) ECMA n/a |
|
|
IE for Windows includes a scripting feature called conditional compilation. It is a mode that, once turned on via the @cc_on statement, allows JScript statements to run under conditions that are testable within this conditional environment. If you surround conditional compilation statements by JavaScript comments, the conditional statements run only in IE 4 or later for Windows, while not conflicting with other browsers. |
|
The "conditional" part comes from numerous global properties (all preceded with the @ symbol) that reveal environmental properties, such as script engine version, operating system, and CPU type. All of this information is available from the navigator object's properties on a wide range of browsers, so this is not unique information available only to this conditional environment. |
|
To engage conditional compilation, include the following statement in your script: /*@cc_on @*/ |
|
This is a one-way toggle: once the mode is turned on, it can't be turned off in the current page. |
|
The following fragment shows how the @if and related statements display some environmental information in the window's status bar if the browser is running JScript Version 5.6 or later (IE 6 or later): /*@cc_on @*/ /*@if (@_jscript_version>= 5.6 && @_x86) status = "Now running JScript version " + @_jscript_version + " with Intel inside."; @else @*/ status = "Have a nice day."; /*@end @*/ |
|
The @set statement lets you assign a numeric or Boolean value (no strings) to a variable (a variable with an @ prefix) within a conditional compilation section: @set @isOK = @_win32 |
|
Once initialized, that variable (including its otherwise unacceptable identifier) can be used in script statements throughout the page. Note that the Visual Basic-inspired syntax of @ statements in conditional compilation statements does not permit semicolons at the end of statements. |
|
On the one hand, conditional compilation could be useful for IE-only deployment to screening older IE versions from new language features that would generate compilation errors (such as try-catch constructions) because such statements compile only under very controllable version situations. In a multibrand browser development shop, however, at most you might find application for IE-only debugging purposes, but probably not for actual application deployment. |
|
Example | |
See the discussion above. |
@cc_on, @if, @end, @set | NN n/a IE 4(Win) ECMA n/a |
|
|
IE for Windows includes a scripting feature called conditional compilation. It is a mode that, once turned on via the @cc_on statement, allows JScript statements to run under conditions that are testable within this conditional environment. If you surround conditional compilation statements by JavaScript comments, the conditional statements run only in IE 4 or later for Windows, while not conflicting with other browsers. |
|
The "conditional" part comes from numerous global properties (all preceded with the @ symbol) that reveal environmental properties, such as script engine version, operating system, and CPU type. All of this information is available from the navigator object's properties on a wide range of browsers, so this is not unique information available only to this conditional environment. |
|
To engage conditional compilation, include the following statement in your script: /*@cc_on @*/ |
|
This is a one-way toggle: once the mode is turned on, it can't be turned off in the current page. |
|
The following fragment shows how the @if and related statements display some environmental information in the window's status bar if the browser is running JScript Version 5.6 or later (IE 6 or later): /*@cc_on @*/ /*@if (@_jscript_version>= 5.6 && @_x86) status = "Now running JScript version " + @_jscript_version + " with Intel inside."; @else @*/ status = "Have a nice day."; /*@end @*/ |
|
The @set statement lets you assign a numeric or Boolean value (no strings) to a variable (a variable with an @ prefix) within a conditional compilation section: @set @isOK = @_win32 |
|
Once initialized, that variable (including its otherwise unacceptable identifier) can be used in script statements throughout the page. Note that the Visual Basic-inspired syntax of @ statements in conditional compilation statements does not permit semicolons at the end of statements. |
|
On the one hand, conditional compilation could be useful for IE-only deployment to screening older IE versions from new language features that would generate compilation errors (such as try-catch constructions) because such statements compile only under very controllable version situations. In a multibrand browser development shop, however, at most you might find application for IE-only debugging purposes, but probably not for actual application deployment. |
|
Example | |
See the discussion above. |
?: | 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. |
|
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"; |
continue | NN 2 IE 3 ECMA 1 |
|
|
Stops execution of the current iteration through the loop and returns to the top of the loop for the next pass (executing the update expression if one is specified in a for loop). If you are using nested loop constructions, assign labels to each nested layer, and use the desired label as a parameter with the continue statement. See the label statement (available only starting with Navigator 4 and Internet Explorer 4). |
|
Example | |
outerLoop: for (var i = 0; i <= maxValue1; i++) { for (var j = 0; j <= maxValue2; j++) { if (j*i == magic2) { continue outerLoop; } } } |
/char | NN 2 IE 3 ECMA 1 | |||||||||||||||||||
|
||||||||||||||||||||
JavaScript provides a mechanism for including common whitespace characters (sometimes called control codes) inside strings, as well as symbols that otherwise conflict with string representation. The key is the backslash character (\), followed immediately by a single character with a special meaning. The following table shows the recognized escaped characters and their meanings. |
||||||||||||||||||||
These characters come in handy for alert, confirm, and prompt dialog box text. For example, if you want to display multiple paragraphs with a blank line between them in an alert box, you would insert line feed characters: alert("First paragraph.\n\nSecond paragraph.") |
||||||||||||||||||||
Note that these characters apply to strings, and do not influence HTML content formatting for carriage returns. |
||||||||||||||||||||
|
— | 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-- |
delete | NN 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; |
/ | 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; |
do/while | NN 4 IE 4 ECMA 3 |
|
|
Executes statements in a loop while a condition is true. Because the condition is tested at the end of the loop, the statements inside it are always executed at least one time. It is imperative that the expression that makes up the condition have some aspect of its value potentially altered in the statements. Otherwise, an infinite loop occurs. |
|
Example | |
var i = 1; do { window.status = "Loop number " + i++; } while (i <= 10) window.status = ""; |
== | 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.
|
||||||||||||||||
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-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 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) { ... } |
if | NN 2 IE 3 ECMA 1 |
|
|
This is a simple conditional statement that provides one alternate execution path. |
|
Example | |
if (myDateObj.getMonth( ) == 1) { calcMonthLength( ); } |
if/else | NN 2 IE 3 ECMA 1 |
|
|
This is a conditional statement that provides two execution paths depending on the result of the condition. You can nest another if or if/else statement inside either path of the if/else statement. |
|
Example | |
var theMonth = myDateObj.getMonth( ); if (theMonth == 1) { monLength = calcLeapMonthLength( ); } else { monLength = calcMonthLength(theMonth); } |
in | NN 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( ) } |
++ | 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: |
|
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) { ... } |
instanceof | NN 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 } |
<= | 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 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 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; |
new | NN 2 IE 3 ECMA 1 |
|
|
The new operator creates instances of the following ECMA standard static objects:
|
|
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( ); |
! | 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:
|
|
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 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 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) { ... } |
for | NN 2 IE 3 ECMA 1 |
|
|
This is a construction that allows repeated execution of statements, usually for a controlled number of times. |
|
Example | |
var userEntry = document.forms[0].entry.value; var oneChar; for (var i = 0; i < userEntry.length; i++) { oneChar = userEntry.charAt(i); if (oneChar < "0" || oneChar > "9") { alert("The entry must be numerals only."); } } |
for/in | NN 2 IE 3 ECMA 1 |
|
|
This is a variation of the regular for loop that can extract the property names and values of an object. Only properties (and, in Netscape 6, methods) that are set to be enumerable by the browser internals appear in the output of this construction. Opera 6 supports this construction only for custom script-generated objects. |
|
Example | |
function showProps( ) { objName = "image"; obj = document.images[0]; var msg = ""; for (var i in obj) { msg += objName + "." + i + "=" + obj[i] + "\n"; } alert(msg); } |
- | 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; |
switch/case | NN 4 IE 4 ECMA 3 |
|
|
Provides a shortcut to execution paths for numerous conditions of an expression. The optional break statement at the end of each case block shortcuts execution of the switch statement, and also prevents the inadvertent execution of the default block, if present. |
|
Example | |
var productList = document.forms[0].prodList; var chosenItem = productList.options[productList.selectedIndex].value; switch(chosenItem) { case "Small Widget": document.forms[0].price.value = "44.95"; break; case "Medium Widget": document.forms[0].price.value = "54.95"; break; case "Large Widget": document.forms[0].price.value = "64.95"; break; default: document.forms[0].price.value = "Nothing Selected"; } |
this | NN 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);"> |
throw | NN 6 IE 5 ECMA 3 |
|
|
Triggers an exception condition, passing a value along with the exception. Although the value you pass can be a simple string, ideally you should pass an instance of the JavaScript Error object filled with sufficient information for a catch statement to act intelligently on the error. A throw statement must be enclosed in the try portion of a try-catch construction. |
|
Example | |
function processNumber(inputField) { try { var inpVal = parseInt(inputField.value, 10); if (isNaN(inpVal)) { var msg = "Please enter a number only."; var err = new Error(msg); if (!err.message) { err.message = msg; } throw err; } // process number } catch (e) { alert(e.message); inputField.focus( ); inputField.select( ); } } |
try/catch | NN 6 IE 5 ECMA 3 |
|
|
This construction provides a nondisruptive way to trap for errors (exceptions) and handle them gracefully. Both parts of this exception-handling construction are required. If an error occurs in the try portion, execution immediately branches to the catch portion, where your scripts can display alert dialogs, modify data, or any other task that keeps the JavaScript interpreter from triggering a disruptive error message. Exceptions that occur naturally (i.e., they are not thrown by a throw statement) pass an instance of the Error object as a parameter to the catch section. Statements inside the catch section can examine properties of the error object to determine how to handle exceptions that land there. Thus, one catch portion can handle errors of various types. |
|
You can use try/catch constructions only in browsers that support them. To protect older browsers from seeing this construction, place all affected code inside a <script> tag that explicitly requires JavaScript 1.5 or later (with the language = "JavaScript1.5" attribute. |
|
Example | |
function insertOneNode(baseNode, newNode, position) { try { baseNode.insertBefore(newNode, baseNode.childNodes[position]); } catch (e) { // handle W3C DOM Exception types switch (e.name) { case "HIERARCHY_REQUEST_ERR" : // process bad tree hierarchy reference break; case "NOT_FOUND_ERR" : // process bad refNode reference break; default : // process all other exceptions } } return true; } |
typeof | NN 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:
|
|
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") { ... } |
void | NN 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> |
while | NN 2 IE 3 ECMA 1 |
|
|
Executes statements in a loop as long as a condition is true. Because the condition is tested at the beginning of the loop, it is conceivable that under the right conditions, the statements inside the loop do not execute. It is imperative that the expression that makes up the condition have some aspect of its value potentially altered in the statements. Otherwise an infinite loop occurs. |
|
Example | |
var i = 0; while (!document.forms[0].radioGroup[i].checked) { i++; } alert("You selected item number " + (i+1) + "."); |
with | NN 2 IE 3 ECMA 1 |
|
|
The with statement adds an object to the scope of every statement nested within. This can shorten the code of some statement groups that rely on a particular object reference. Note that with constructions are generally very inefficient. You can achieve better performance by assigning the object reference to a local variable, and using that variable in your function. |
|
Example | |
with (document.forms[0]) { name1 = firstName.value; name2 = lastName.value; mail = eMail.value; } |
return | NN 2 IE 3 ECMA 1 |
|
|
Stops execution of the current function. A return statement can be located anywhere within the function, including inside control structures. You can optionally specify a value to be returned to the calling statement. This return value can be any JavaScript data type. If a return statement that returns a value is in a loop or other control structure, there must be a return statement for each branch of the execution tree, including a default return statement if execution should reach the main execution scope near or at the end of the function. |
|
Example | |
function validateNumber(form) { var oneChar; for (var i = 0; i < userEntry.length; i++) { oneChar = form.entry.value.charAt(i); if (oneChar < "0" || oneChar > "9") { return false; } } return true; } |
+= | NN 2 IE 3 ECMA 1 | |||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
This is the add-by-value operator. This class of operator combines a regular assignment operator (=) with one of the many other operators to carry out the assignment by performing the stated operation on the left operand with the value of the right operand. For example, if a variable named a has a string stored in it, you can append a string to a with the += operator: 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. |
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
Example | ||||||||||||||||||||||||||||||||||||
output += "<H1>Section 2</H1>"; total *= .95; |
+ | 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.
|
|||||||||||||||||
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) { ... } |
break | NN 2 IE 3 ECMA 1 |
|
|
Stops execution of the current loop and returns control to the next script statement following the end of the current loop. Note that without a label parameter, the scope of the break statement is its own loop. To break out of a nested loop, assign labels to each nested layer, and use the desired label as a parameter with the break statement. See the label statement (available only starting with Navigator 4 and Internet Explorer 4). |
|
Example | |
See the label statement. |
continue | NN 2 IE 3 ECMA 1 |
|
|
Stops execution of the current iteration through the loop and returns to the top of the loop for the next pass (executing the update expression if one is specified in a for loop). If you are using nested loop constructions, assign labels to each nested layer, and use the desired label as a parameter with the continue statement. See the label statement (available only starting with Navigator 4 and Internet Explorer 4). |
|
Example | |
outerLoop: for (var i = 0; i <= maxValue1; i++) { for (var j = 0; j <= maxValue2; j++) { if (j*i == magic2) { continue outerLoop; } } } |
catch | NN 2 IE 3 ECMA 1 |
|
|
See try. |