Team LiB
Previous Section Next Section

Operators

JavaScript has a wealth of operators that are similar to C/C++ but with some additions to deal with weak typing and some minor omissions due to the fact the language generally does not access the disk or memory.

Note

We take some liberty with the following categorization of operators. We believe that our categories (and placement of operators) make the operators easier to understand.

Arithmetic Operators

Arithmetic operators operate on numbers, with one exception: +, which is overloaded and provides string concatenation as well. Tables A-18, A-19, and A-20 detail the arithmetic operators found in JavaScript.

Table A-18: Binary (Two-Operand) and Self-assignment Arithmetic Operators

Operator

Self-assignment Operator

Operation

+

+=

Addition (also functions as string concatenation)

–=

Subtraction

*

*=

Multiplication

/

/=

Division

%

%=

Modulus (the integer remainder when the first operand is divided by the second)

Table A-19: Pre/Postfix Arithmetic Operators

Operator

Description

++

Auto-increment (increment the value by one and store)

--

Auto-decrement (decrement the value by one and store)

Table A-20: Unary (One Operand) Arithmetic Operators

Operator

Description

+

Has no effect on numbers but causes non-numbers to be converted into numbers

Negation (changes the sign of the number or converts the expression to a number and then changes its sign)

Bitwise Operators

Bitwise operators operate upon integers in a bit-by-bit fashion. Most computers store negative numbers using their two’s complement representation, so you should exercise caution when performing bit operations on negative numbers. Most uses of JavaScript rarely involve bitwise operators but they are presented in Table A-21 for those so inclined to use them.

Table A-21: Binary and Self-assignment Bitwise Operators

Operator

Self-assignment Operator

Description

<<

<<=

Bitwise left shift the first operand by the value of the second operand, zero filling “vacated” bit positions

>>

>>=

Bitwise right shift the first operand by the value of the second operand, sign filling the “vacated” bit positions

>>>

>>>=

Bitwise left right shift the first operand by the value of the second operand, zero filling “vacated” bit positions

&

&=

Bitwise AND

|

|=

Bitwise OR

^

^=

Bitwise XOR (exclusive OR)

~

N/A

Bitwise negation is a unary operator and takes only one value. It converts the number to a 32-bit binary number, and then inverts 0 bits to 1 and 1 bits to 0 and converts back.

Logical Operators

Logical operators operate upon Boolean values and are used to construct conditional statements. Logical operators are short-circuited in JavaScript, meaning that once a logical condition is guaranteed, none of the other sub-expressions in a conditional expression are evaluated. They are evaluated left to right. Table A-22 summarizes these operators.

Table A-22: Binary Logical Operators

Operator

Description

Example

&&

Logical AND

true && false

||

Logical OR

true || false

!

Logical negation

! true

Conditional Operator

The conditional operator is a ternary operator popular among C programmers. Its syntax is

( expr1 ? expr2 : expr3 )

where expr1 is an expression evaluating to a Boolean and expr2 and expr3 are expressions. If expr1 evaluates true, then the expression takes on the value expr2; otherwise, it takes on the value expr3.

Type Operators

Type operators generally operate on objects or object properties. The most commonly used operators are new and typeof, but JavaScript supports a range of other type operators as well, summarized in Table A-23.

Table A-23: Binary Type Operators

Operator

Description

Example

delete

If the operand is an array element or object property, the operand is removed from the array or object.

var myArray = [1,3,5];
delete myArray[1];
alert(myArray);
// shows [1,,5]

instanceof

Evaluates true if the first operand is an instance of the second operand. The second operand must be an object (for example, a constructor).

var today = new Date();
alert(today instanceof Date);
// shows true

in

Evaluates true if the first operand (a string) is the name of a property of the second operand. The second operand must be an object (for example, a constructor).

var robot = {jetpack:true}
alert("jetpack" in robot);
// alerts true
alert("x-ray vision" in robot);
// alerts false

new

Creates a new instance of the object given by the constructor operand.

var today = new Date();
alert(today);

void

Effectively undefines the value of its expression operand

var myArray = [1,3,5];
myArray = void myArray;
alert(myArray);
// shows undefined

Also included in the type operators is the property-accessing operator. To access a property property of an object object, the following two syntaxes are equivalent:

object.property

object["property"]

Note that the brackets above are “real” brackets (they do not imply an optional component).

Comma Operator

The comma operator allows multiple statements to be carried out as one. The syntax of the operator is

statement1, statement2 [, statement3] ...

If used in an expression, its value is the value of the last statement. The comma is commonly used to separate variables in declarations or parameters in function calls.

Relational Operators

Relational operators, as detailed in Table A-24, are binary operators that compare two like types and evaluate to a Boolean indicating whether the relationship holds. If the two operands are not of the same type, type conversion is carried out so that the comparison can take place (see the section immediately following for more information).

Table A-24: Binary Relational Operators

Operator

Description

<

Evaluates true if the first operand is less than the second

<=

Evaluates true if the first operand is less than or equal to the second

>

Evaluates true if the first operand is greater than the second

>=

Evaluates true if the first operand is greater than or equal to the second

!=

Evaluates true if the first operand is not equal to the second

==

Evaluates true if the first operand is equal to the second

!==

Evaluates true if the first operand is not equal to the second (and they have the same type)

===

Evaluates true if the first operand is equal to the second (and they have the same type)

Type Conversion in Comparisons

A JavaScript implementation should carry out the following steps in order to compare two different types:

  1. If both of the operands are strings, compare them lexicographically.

  2. Convert both operands to numbers.

  3. If either operand is NaN, return undefined (which in turn evaluates to false when converted to a Boolean).

  4. If either operand is infinite or zero, evaluate the comparison using the rules that +0 and –0 compare false unless the relation includes equality, that Infinity is never less than any value, and that –Infinity is never more than any value.

  5. Compare the operands numerically.

Note

Using the strict equality (===) or inequality (!==) operator on operands of two different types will always evaluate false.

Lexicographic Comparisons

The lexicographic comparisons performed on strings adhere to the following guidelines. Note that a string of length n is a “prefix” of some other string of length n or more if they are identical in their first n characters. So, for example, a string is always a prefix of itself.

  • If two strings are identical, they are equal (note that there are some very rare exceptions when two strings created using different character sets might not compare equal, but this almost never happens).

  • If one string is a prefix of the other (and they are not identical), then it is “less than” the other. (For example, “a” is less than “aa.”)

  • If two strings are identical up to the nth (possibly 0th) character, then the (n + 1)st character is examined. (For example, the third character of “abc” and “abd” would be examined if they were to be compared.)

  • If the numeric value of the character code under examination in the first string is less than that of the character in the second string, the first string is “less than” second. (The relation 1 < 9 < A < Z < a < z is often helpful for remembering which characters come “less” than others.)

Operator Precedence and Associativity

JavaScript assigns a precedence and associativity to each operator so that expressions will be well-defined (that is, the same expression will always evaluate to the same value). Operators with higher precedence evaluate before operators with lower precedence. Associativity determines the order in which identical operators evaluate. Given the expression

a b c

a left-associative operator would evaluate

(a b) c

while a right-associative operator would evaluate

a (b c)

Table A-25 summarizes operator precedence and associativity in JavaScript.

Table A-25: Precedence and Associativity of JavaScript Operators

Precedence

Associativity

Operator

Operator Meanings

Highest

Left

., [ ], ()

Object property access, array or object property access, parenthesized expression

Right

++, ––, , ~, !, delete, new, typeof, void

Pre/post increment, pre/post decrement, arithmetic negation, bitwise negation, logical negation, removal of a property, object creation, getting data type, undefine a value

Left

*, /, %

Multiplication, division, modulus

Left

+,

Addition (arithmetic) and concatenation (string), subtraction

Left

<<, >>, >>>

Bitwise left shift, bitwise right shift, bitwise right shift with zero fill

Left

<, <=, >, >=, in, instanceof

Less than, less than or equal to, greater than, greater than or equal to, object has property, object is an instance of

Left

==, !=, ===, !===

Equality, inequality, equality (with type checking), inequality (with type checking)

Left

&

Bitwise AND

Left

^

Bitwise XOR

Left

|

Bitwise OR

Left

&&

Logical AND

Left

||

Logical OR

Right

? :

Conditional

Right

=

Assignment

Right

*=, /=, %=, +=, –=, <<=, >>=, >>>=, &=, ^=, |=

Operation and self-assignment

Lowest

Left

,

Multiple evaluation


Team LiB
Previous Section Next Section