Cover by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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 logical

* / %

Arithmetic

+ -

Arithmetic ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required