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).
Operator | Used for | Example |
Arithmetic | Basic mathematics | |
Array | Array manipulation | |
Assignment | Assigning values | |
Bitwise | Manipulating bits within bytes | |
Comparison | Comparing two values | |
Increment/Decrement | Adding or subtracting 1 | |
Logical | Boolean comparison | |
String | Concatenation | |
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-lineifstatement 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.
Operator(s) | Type(s) |
| Parentheses, call, and member |
| Increment/decrement |
| Unary, bitwise, and logical |
|
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access