Operators

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

Table 15-1. JavaScript operator types

Operator

Description

Example

Arithmetic

Basic mathematics

a + b

Array

Array manipulation

a + b

Assignment

Assign values

a = b + 23

Bitwise

Manipulate bits within bytes

12 ^ 9

Comparison

Compare two values

a < b

Increment/Decrement

Add or subtract one

a++

Logical

Boolean

a && b

String

Concatenation

a + 'string'

Each operator takes 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.

  • One ternary operator, which takes the form ? x : y. It’s a terse single-line if statement that chooses between two expressions depending on a third one.

Operator Precedence

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

Table 15-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 and string

<< >> >>>

Bitwise

&

Bitwise

|

Bitwise

^

Bitwise

< > <= >=

Comparison

== != === !==

Comparison

&&

Logical

||

Logical

? :

Ternary

= += -= *= /= %= <<= ...

Get Learning PHP, MySQL, and JavaScript 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.