Chapter

6

Expressions and operators

his chapter describes JavaScript expressions and operators, including assignment operators, arithmetic, bitwise, logical, and comparison operators..

Expressions

An expression is any valid set of literals, variables, operators, and expressions that evaluates to a single value; the value can be a number, a string, or a logical value.

Conceptually, there are two types of expressions: those that assign a value to a variable, and those that simply have a value. For example, the expression x = 7 is an expression that assigns x the value seven. This expression itself evaluates to seven. Such expressions use assignment operators. On the other hand, the expression 3 + 4 simply evaluates to seven; it does not perform an assignment. The operators used in such expressions are referred to simply as operators.

JavaScript has the following types of expressions:

Conditional expressions

A conditional expression can have one of two values based on a condition. The syntax is

(condition) ? val1 : val2
If condition is true, the expression has the value of val1. Otherwise it has the value of val2. You can use a conditional expression anywhere you would use a standard expression.

For example,

status = (age >= 18) ? "adult" : "minor"
This statement assigns the value "adult" to the variable status if age is eighteen or greater. Otherwise, it assigns the value "minor" to status.

Assignment operators

An assignment operator assigns a value to its left operand based on the value of its right operand. 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 operators are shorthand for standard operations, as shown in the following table:
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

Comparison operators

A comparison operator compares its operands and returns a logical value based on whether the comparison is true or not. The operands can be numerical or string values. When used on string values, the comparisons are based on the standard lexicographical ordering. They are described in the following table.
Operator

Description

Example

Equal (= =) Returns true if the operands are equal. x == y returns true if x equals y.
Not equal (!=) Returns true if the operands are not equal. x != y returns true if x is not equal to y.
Greater than (>) Returns true if left operand is greater than right operand. x > y returns true if x is greater than y.
Greater than or equal (>=) Returns true if left operand is greater than or equal to right operand. x >= y returns true if x is greater than or equal to y.
Less than (<) Returns true if left operand is less than right operand. x < y returns true if x is less than y.
Less than or equal (<=) Returns true if left operand is less than or equal to right operand. x <= y returns true if x is less than or equal to y.

Operators

JavaScript has arithmetic, bitwise, logical, and string operators. There are both binary and unary operators. A binary operator requires two operands, one before the operator and one after the operator:

operand1 operator operand2
For example, 3+4 or x*y.

A unary operator requires a single operand, either before or after the operator:

operator operand
or

operand operator
For example, x++ or ++x.

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 (/). These operators work as they do in other programming languages.

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 remainder of integrally 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 three and increments x to four. If x is three, then the statement y = ++x increments x to four and sets y to four.

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 three and decrements x to two. If x is three, then the statement y = --x decrements x to two and sets y to two.

Unary negation

The unary negation precedes its operand and negates it. For example, x = -x negates the value of x; that is, if x were three, it would become -3.

Bitwise operators

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

The following table summarizes JavaScript's bitwise operators
Operator

Usage

Description

Bitwise AND a & b Returns a one in each bit position if bits of both operands are ones.
Bitwise OR a | b Returns a one in a bit if bits of either operand is one.
Bitwise XOR a ^ b Returns a one in a bit position if bits of one but not both operands are one.
Bitwise NOT ~ a Flips 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.

Bitwise logical operators

The bitwise logical operators work conceptually as follows:

Bitwise shift operators

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 take Boolean (logical) values as operands and return a Boolean value. They are described in the following table.
Operator

Usage

Description

and (&&) expr1 && expr2 Returns true if both logical expressions expr1 and expr2 are true. Otherwise, returns false.
or (||) expr1 || expr2 Returns true if either logical expression expr1 or expr2 is true. If both are false, returns false.
not (!) !expr If expr is true, returns false; if expr is false, returns true.

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

String operators

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, "my " + "string" returns the string "my string".

The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable mystring has the value "alpha," then the expression mystring += "bet" evaluates to "alphabet" and assigns this value to mystring.

Operator precedence

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

The following table describes the precedence of operators, from lowest to highest:
Operator

Examples

assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
conditional ?:
logical-or ||
logical-and &&
bitwise-or |
bitwise-xor ^
bitwise-and &
equality == !=
relational < <= > >=
bitwise shift << >> >>>
addition/subtraction + -
multiply/divide * / %
negation/increment ! ~ - ++ --
call, member () [] .