HTML and CSS Reference

In-Depth Information

An assignment statement evaluates the expression on the right side of the equal sign and

assigns the result to the variable on the left side of the equal sign. The equal sign is the

assignment operator.

var total = 5 + 4;

var friend = "Tony";

total

=

5 + 4

variable

assignment

expression

friend

=

"Tony"

When an expression contains a number of operators and operands, such as
5 * 4 + 3 / -2.2
,

and the order of evaluation is ambiguous, then JavaScript must determine what to do.

This is where the precedence and associative rules come in. They tell JavaScript how to

evaluate such an expression. Precedence refers to the way in which the operator binds

to its operand, such as, should addition be done before division or should assignment

come before multiplication? The precedence of one operator over another determines

what operation is done first. As shown in Table 5.1, the operators are organized as a hier-

archy, the operators of highest precedence at the top, similar to a social system where

those with the most power (or money) are at the top. In the rules of precedence, the

multiplication operator is of higher precedence than the addition operator, technically

meaning the operator of higher precedence binds more tightly to its operands. The

assignment operators are low in precedence and thus bind loosely to their operand. In

the expression
sum = 5 + 4
the equal sign is of low precedence, so the expression
5 + 4
is

evaluated first and then the result is assigned to
sum
. Parentheses are of the highest pre-

cedence. An expression placed within parentheses is evaluated first; thus, in the expres-

sion
2 * (10 - 4)
, the expression within the parentheses is evaluated first and that result

is multiplied by
2
. When parentheses are nested, the expression contained within the

innermost set of parentheses is evaluated first.

Associativity refers to the order in which an operator evaluates its operands: left to right

in no specified order, or right to left. When all of the operators in an expression are of equal

precedence, normally the association is left to right; in the expression
5 + 4 + 3
, the evalu-

ation is from left to right. In Example 5.1, how is the expression evaluated? Is addition,

multiplication, or division done first? And in what order, right to left or left to right?