Operators

JavaScript offers a lot of powerful operators, ranging from arithmetic, string, and logical operators to operators for assignment, comparison, and more (see Table 14-1).

Table 14-1. JavaScript operator types

Operator

Used for

Example

Arithmetic

Basic mathematics

a + b

Array

Array manipulation

a + b

Assignment

Assigning values

a = b + 23

Bitwise

Manipulating bits within bytes

12 ^ 9

Comparison

Comparing two values

a < b

Increment/Decrement

Adding or subtracting 1

a++

Logical

Boolean comparison

a && b

String

Concatenation

a + 'string'

Different types of operators take a different number of operands:

  • Unary operators, such as incrementing ($a++) or negation (-$a), take a single operand.

  • Binary operators, which represent the bulk of JavaScript operators (including addition, subtraction, multiplication, and division), take two operands.

  • There is one ternary operator, which takes the form x ? y : z. It’s a terse, single-line if statement that chooses between two expressions, depending on the result of a third one. This conditional operator takes three operands.

Operator Precedence

Like PHP, JavaScript utilizes operator precedence, in which some operators in an expression are considered more important than others and are therefore evaluated first. Table 14-2 lists JavaScript’s operators and their precedences.

Table 14-2. The precedence of JavaScript operators (high to low)

Operator(s)

Type(s)

() [] .

Parentheses, call, and member

++ −−

Increment/decrement

+ − ~ !

Unary, bitwise, and ...

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.