Previous     Contents     Index     Next     
Core JavaScript Reference 1.5



Chapter 5   Chapter 5 Operators


JavaScript has assignment, comparison, arithmetic, bitwise, logical, string, and special operators. This chapter describes the operators and contains information about operator precedence.

The following table summarizes the JavaScript operators.


Table 5.1    JavaScript operators.  

Operator category

Operator

Description

Arithmetic Operators

+

 

(Addition) Adds 2 numbers.  

++

 

(Increment) Adds one to a variable representing a number (returning either the new or old value of the variable).  

-

 

(Unary negation, subtraction) As a unary operator, negates the value of its argument. As a binary operator, subtracts 2 numbers.  

--

 

(Decrement) Subtracts one from a variable representing a number (returning either the new or old value of the variable).  

*

 

(Multiplication) Multiplies 2 numbers.  

/

 

(Division) Divides 2 numbers.  

%

 

(Modulus) Computes the integer remainder of dividing 2 numbers.  

String Operators

+  

(String addition) Concatenates 2 strings.  

+=  

Concatenates 2 strings and assigns the result to the first operand.  

Logical Operators

&&  

(Logical AND) Returns the first operand if it can be converted to false; otherwise, returns the second operand. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.  

||  

(Logical OR) Returns the first operand if it can be converted to true; otherwise, returns the second operand. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.  

!  

(Logical NOT) Returns false if its single operand can be converted to true; otherwise, returns true.  

Bitwise Operators

&

 

(Bitwise AND) Returns a one in each bit position if bits of both operands are ones.  

^

 

(Bitwise XOR) Returns a one in a bit position if bits of one but not both operands are one.  

|

 

(Bitwise OR) Returns a one in a bit if bits of either operand is one.  

~

 

(Bitwise NOT) Flips the bits of its operand.  

<<

 

(Left shift) Shifts its first operand in binary representation the number of bits to the left specified in the second operand, shifting in zeros from the right.  

>>

 

(Sign-propagating right shift) Shifts the first operand in binary representation the number of bits to the right specified in the second operand, discarding bits shifted off.  

>>>

 

(Zero-fill right shift) Shifts the first operand in binary representation the number of bits to the right specified in the second operand, discarding bits shifted off, and shifting in zeros from the left.  

Assignment Operators

=

 

Assigns the value of the second operand to the first operand.  

+=

 

Adds 2 numbers and assigns the result to the first.  

-=

 

Subtracts 2 numbers and assigns the result to the first.  

*=

 

Multiplies 2 numbers and assigns the result to the first.  

/=

 

Divides 2 numbers and assigns the result to the first.  

%=

 

Computes the modulus of 2 numbers and assigns the result to the first.  

&=

 

Performs a bitwise AND and assigns the result to the first operand.  

^=

 

Performs a bitwise XOR and assigns the result to the first operand.  

|=

 

Performs a bitwise OR and assigns the result to the first operand.  

<<=

 

Performs a left shift and assigns the result to the first operand.  

>>=

 

Performs a sign-propagating right shift and assigns the result to the first operand.  

>>>=

 

Performs a zero-fill right shift and assigns the result to the first operand.  

Comparison Operators

==  

Returns true if the operands are equal.  

!=  

Returns true if the operands are not equal.  

===  

Returns true if the operands are equal and of the same type.  

!==  

Returns true if the operands are not equal and/or not of the same type.  

>  

Returns true if the left operand is greater than the right operand.  

>=  

Returns true if the left operand is greater than or equal to the right operand.  

<  

Returns true if the left operand is less than the right operand.  

<=  

Returns true if the left operand is less than or equal to the right operand.  

Special Operators

?:

 

Performs a simple "if...then...else".  

,

 

Evaluates two expressions and returns the result of the second expression.  

delete

 

Deletes an object, an object's property, or an element at a specified index in an array.  

function

 

Defines an anonymous function.  

in

 

Returns true if the specified property is in the specified object.  

instanceof

 

Returns true if the specified object is of the specified object type.  

new

 

Creates an instance of a user-defined object type or of one of the built-in object types.  

this

 

Keyword that you can use to refer to the current object.  

typeof

 

Returns a string indicating the type of the unevaluated operand.  

void

 

Specifies an expression to be evaluated without returning a value.  



Assignment Operators



An assignment operator assigns a value to its left operand based on the value of its right operand.

Implemented in  

JavaScript 1.0  

ECMA version  

ECMA-262  

The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x. The other assignment operators are usually shorthand for standard operations, as shown in the following table.


Table 5.2    Assignment operators

Shorthand operator

Meaning

x += y

 

x = x + y

 

x -= y

 

x = x - y

 

x *= y

 

x = x * y

 

x /= y

 

x = x / y

 

x %= y

 

x = x % y

 

x <<= y

 

x = x << y

 

x >>= y

 

x = x >> y

 

x >>>= y

 

x = x >>> y

 

x &= y

 

x = x & y

 

x ^= y

 

x = x ^ y

 

x |= y

 

x = x | y

 

In unusual situations, the assignment operator is not identical to the Meaning expression in Table 5.2. When the left operand of an assignment operator itself contains an assignment operator, the left operand is evaluated only once. For example:

a[i++] += 5 //i is evaluated only once
a[i++] = a[i++] + 5 //i is evaluated twice



Comparison Operators



A comparison operator compares its operands and returns a logical value based on whether the comparison is true.

Implemented in  

JavaScript 1.0

JavaScript 1.3: Added the === and !== operators.

JavaScript 1.4: Deprecated == for comparison of two JSObject objects. Use the JSObject.equals method.  

ECMA version  

ECMA-262 includes all comparison operators except === and !==.
ECMA-262 Edition 3 adds === and !==.
 

The operands can be numerical or string values. Strings are compared based on standard lexicographical ordering, using Unicode values.

A Boolean value is returned as the result of the comparison.

  • Two strings are equal when they have the same sequence of characters, same length, and same characters in corresponding positions.

  • Two numbers are equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal.

  • Two objects are equal if they refer to the same Object.

  • Two Boolean operands are equal if they are both true or false.

  • Null and Undefined types are == (but not ===).
The following table describes the comparison operators.


Table 5.3    Comparison operators

Operator

Description

Examples returning true1

Equal (==)  

Returns true if the operands are equal. If the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison.  

3 == var1
"3" == var1
3 == '3'

 

Not equal (!=)  

Returns true if the operands are not equal. If the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison.  

var1 != 4
var1 != "3"

 

Strict equal (===)  

Returns true if the operands are equal and of the same type.  

3 === var1

 

Strict not equal (!==)  

Returns true if the operands are not equal and/or not of the same type.  

var1 !== "3"
3 !== '3'

 

Greater than (>)  

Returns true if the left operand is greater than the right operand.  

var2 > var1

 

Greater than or equal (>=)  

Returns true if the left operand is greater than or equal to the right operand.  

var2 >= var1
var1 >= 3

 

Less than (<)  

Returns true if the left operand is less than the right operand.  

var1 < var2

 

Less than or equal (<=)  

Returns true if the left operand is less than or equal to the right operand.  

var1 <= var2
var2 <= 5

 

1 These examples assume that var1 has been assigned the value 3 and var2 has been assigned the value 4.


Using the Equality Operators

The standard equality operators (== and !=) compare two operands without regard to their type. The strict equality operators (=== and !==) perform equality comparisons on operands of the same type. Use strict equality operators if the operands must be of a specific type as well as value or if the exact type of the operands is important. Otherwise, use the standard equality operators, which allow you to compare the identity of two operands even if they are not of the same type.

When type conversion is needed, JavaScript converts String, Number, Boolean, or Object operands as follows.

  • When comparing a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.

  • If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.

  • If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects. If this attempt to convert the object fails, a runtime error is generated.
You cannot use the standard equality operator (==) to compare instances of JSObject. Use the JSObject.equals method for such comparisons.


Backward Compatibility
The behavior of the standard equality operators (== and !=) depends on the JavaScript version.

JavaScript 1.3 and earlier versions. You can use either the standard equality operator (==) or JSObject.equals to compare instances of JSObject.

JavaScript 1.2. The standard equality operators (== and !=) do not perform a type conversion before the comparison is made. The strict equality operators (=== and !==) are unavailable.

JavaScript 1.1 and earlier versions. The standard equality operators (== and !=) perform a type conversion before the comparison is made. The strict equality operators (=== and !==) are unavailable.



Arithmetic Operators



Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).



Implemented in  

JavaScript 1.0  

ECMA version  

ECMA-262  

These operators work as they do in most other programming languages, except the / operator returns a floating-point division in JavaScript, not a truncated division as it does in languages such as C or Java. For example:

1/2 //returns 0.5 in JavaScript
1/2 //returns 0 in Java


% (Modulus)

The modulus operator is used as follows:

var1 % var2

The modulus operator returns the first operand modulo the second operand, that is, var1 modulo var2, in the preceding statement, where var1 and var2 are variables. The modulo function is the integer remainder of dividing var1 by var2. For example, 12 % 5 returns 2.


++ (Increment)

The increment operator is used as follows:

var ++ or ++var

This operator increments (adds one to) its operand and returns a value. If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing. If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.

For example, if x is three, then the statement y = x++ sets y to 3 and increments x to 4. If x is 3, then the statement y = ++x increments x to 4 and sets y to 4.


-- (Decrement)

The decrement operator is used as follows:

var -- or --var

This operator decrements (subtracts one from) its operand and returns a value. If used postfix (for example, x--), then it returns the value before decrementing. If used prefix (for example, --x), then it returns the value after decrementing.

For example, if x is three, then the statement y = x-- sets y to 3 and decrements x to 2. If x is 3, then the statement y = --x decrements x to 2 and sets y to 2.


- (Unary Negation)

The unary negation operator precedes its operand and negates it. For example, y = -x negates the value of x and assigns that to y; that is, if x were 3, y would get the value -3 and x would retain the value 3.



Bitwise Operators



Bitwise operators treat their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators:


Table 5.4    Bitwise operators

Operator

Usage

Description

Bitwise AND  

a & b

 

Returns a one in each bit position for which the corresponding bits of both operands are ones.  

Bitwise OR  

a | b

 

Returns a one in each bit position for which the corresponding bits of either or both operands are ones.  

Bitwise XOR  

a ^ b

 

Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.  

Bitwise NOT  

~ a

 

Inverts the bits of its operand.  

Left shift  

a << b

 

Shifts a in binary representation b bits to left, shifting in zeros from the right.  

Sign-propagating right shift  

a >> b

 

Shifts a in binary representation b bits to right, discarding bits shifted off.  

Zero-fill right shift  

a >>> b

 

Shifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.  




Implemented in  

JavaScript 1.0  

ECMA version  

ECMA-262  

"> Bitwise Logical Operators



Implemented in  

JavaScript 1.0  

ECMA version  

ECMA-262  



Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones).

  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.

  • The operator is applied to each pair of bits, and the result is constructed bitwise.
For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:
  • 15 & 9 yields 9 (1111 & 1001 = 1001)

  • 15 | 9 yields 15 (1111 | 1001 = 1111)

  • 15 ^ 9 yields 6 (1111 ^ 1001 = 0110)




Implemented in  

JavaScript 1.0  

ECMA version  

ECMA-262  

"> Bitwise Shift Operators



Implemented in  

JavaScript 1.0  

ECMA version  

ECMA-262  



The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operator.


<< (Left Shift)

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

For example, 9<<2 yields thirty-six, because 1001 shifted two bits to the left becomes 100100, which is thirty-six.


>> (Sign-Propagating Right Shift)

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left.

For example, 9>>2 yields two, because 1001 shifted two bits to the right becomes 10, which is two. Likewise, -9>>2 yields -3, because the sign is preserved.


>>> (Zero-Fill Right Shift)

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left.

For example, 19>>>2 yields four, because 10011 shifted two bits to the right becomes 100, which is four. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.



Logical Operators



Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.



Implemented in  

JavaScript 1.0  

ECMA version  

ECMA-262  

The logical operators are described in the following table.


Table 5.5    Logical operators

Operator