Understanding the order in which operations are carried out is of paramount importance in programming. Think about the following expression:
3 + 7 * 2
Depending upon how we interpret the equation, the answer could be 17 or 20. If we add three and seven first, we end up with 10 * 2, or 20. Likewise, if we multiply seven and two first, we get 3 + 14, or 17. The notion of which operations to perform first is called precedence. Operations with a higher precedence are executed first, and next the operations with the next-highest precedence. In situations where two operators have an equal precedence, statements are evaluated from left to right.
The table 'Operator Precedence' shows JavaScript's operators and their relative precedence. It is important to understand how precedence relates to all of the operators. Consider the following example:
BooleanA || BooleanB && BooleanC
Is the conditional True if BooleanA, or both BooleanB and BooleanC, are true? Or is it True if either BooleanA or BooleanB, and BooleanC are True? This leads to the discussion of parentheses (). Parentheses have a higher precedence than any other operator and are used to group operators and operands to be evaluated first. Looking back to our first example, if we intended the expression to evaluate to 20, we would have to write (3 + 7) * 2, which would produce the correct answer (multiplication has a higher precedence than addition). Parenthesis can also be used to clarify statements that otherwise might be confusing. The previous conditional could be expressed BooleanA || (BooleanB && BooleanC). Although the meaning of the statement hasn't changed, it is easier to understand what the intended operation is.
|