liveBook · Manning

Operator precedence

As explained in Pro Angular 16

Operator precedence is the rule determining the order in which operators in an expression are evaluated.

Operator precedence determines which operation JavaScript performs first when an expression contains multiple operators. It can interact with automatic type conversion, producing results that differ from the apparent intent. section 3.4.7

Table 3.3. Useful JavaScript operators
Operator
Description
++, --
Pre- or post-increment and decrement
+, -, *, /, %
Addition, subtraction, multiplication, division, remainder
<, <=, >, >=
Less than, less than or equal to, more than, more than or equal to
==, !=
Equality and inequality tests
===, !==
Identity and nonidentity tests
&&, ||
Logical AND and OR
||, ??
Null and null-ish coalescing operators
?
Optional chaining operator
=
Assignment
+
String concatenation
?:
Three-operand conditional statement

Use the operator table to compare arithmetic, comparison, logical, coalescing, optional chaining, assignment, concatenation, and conditional operators. section 3.4.7

Addition versus concatenation

The expression `5 + 5` produces the number `10`, while `5 + "5"` produces the string `"55"`. String concatenation takes precedence over addition in the relevant mixed-type expression, and JavaScript converts values freely. Convert deliberately when the intended operation matters: `(5).toString() + String(5)` produces a string, whereas `Number("5") + parseInt("5")` produces the number `10`. section 3.4.7

Avoid ambiguous expressions by making both the operation and the expected type explicit.

  • Use parentheses before calling a method on a numeric literal, as in `(5).toString()`. section 3.4.7
  • Convert strings with `Number` or `parseInt` when arithmetic is intended. section 3.4.7
  • Inspect both the value and `typeof` result when an expression may combine operators and types. section 3.4.7

How Pro Angular 16 covers it

How deep it goes
Explains precedence through mixed addition and concatenation, but does not provide a complete precedence hierarchy.
Examples
Uses `5 + 5`, `5 + "5"`, explicit string conversion, and explicit numeric conversion to contrast resulting values and types.
What it assumes
Assumes familiarity with JavaScript expressions and operators while demonstrating conversion techniques directly.
What you can do after
Diagnose surprising expression results and choose explicit conversions for concatenation or arithmetic.
How it connects
Connects operator precedence with type conversion, string concatenation, addition, parentheses, and number parsing.

Also explained in

Compare how 7 books explain operator precedence →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.