19 + 23 //The + operator for adding two operands.
//The expression returns 42.
typeof true //The typeof operator for determining the type of
//an operand. It returns "boolean".
Consider, for example, the following expression. What value does it return?
2 * 4 + 3 * 3
Maria: 17.
Professor: And how do you know that?
Maria: Because two times four equ als eight, thr ee times three equa ls n ine, and, finally,
eight p lus nine equals 17.
Professor: I see you are alread y familiar with operator precedence. Just as you learned
in primary school that multiplication is done befor e addition, JavaScript precisely de-
fines which operato r has precedence over which.
What about the next expression? What value does it return?
5 - 4 - 3
Mike: -2.
Professor: Because you computed it righ t, I assume you already know ab out op erator
associativity. Associativity defines w hether oper ators with the same prec edence are
executed from left to right or from right to left. Subtrac tion has left-to-right associa-
tivity, as do most of the JavaScript operators that take two operands. You will find
JavaScript ope rators organized by precedence, with additio nal information about their
associativity in the JavaScript Mini Reference on page 373.
If yo u don’t like precedence and associativity of an operator, you can always change
the order of execution using parentheses—the op erators within parentheses will be
evaluated first. For example, if you want th e subexpression 4 - 3 in the above ex-
pression to be evaluated first, then you simply enclose it in pa rentheses:
5 - (4 - 3) //Returns 4
Arithmetic Operators
Professor: I would now like to go through some of the JavaScript operators that you
will most likely use in your programs. First, there are arithm etic operators, and you
won’t be surprised that they include operator s for addition (+), subtractio n (-), mul-
tiplication (*), and division (/). As you alre ady know from primar y school mathe-
matics, the second two have prec edence over th e first two, and all have left-to-right
associativity. The subtraction operator c an be used as a negative sign operator as well,
6.5. Operators a nd Expressions 115