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-lineif
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.
Operator(s) | Type(s) |
| Parentheses, call, and member |
| Increment/decrement |
| Unary, bitwise, and logical |
|
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.