let
x
;
x
=
3
*
5
;
The first line is a declaration statement; we are declaring the variable
x
. Of course we
could have combined these two lines, but that would confuse this discussion. What’s
more interesting is the second line: there are actually two combined expressions in
that line. The first expression is
3 * 5
, a multiplication expression that resolves to the
value
15
. Then, there’s an assignment expression that assigns the value
15
to the vari‐
able
x
. Note that the assignment is itself an expression, and we know that an expres‐
sion resolves to a value. So what does the assignment expression resolve to? As it
turns out, assignment expressions resolve quite reasonably to the value that was
assigned. So not only is
x
assigned the value
15
, but the whole expression also resolves
to the value
15
. Because the assignment is an expression that resolves to a value, we
could in turn assign it to another variable. Consider the following (very silly)
example:
let
x
,
y
;
y
=
x
=
3
*
5
;
Now we have two variables,
x
and
y
, that both contain the value
15
. We are able to do
this because multiplication and assignment are both expressions. When JavaScript
sees combined expressions like this, it has to break the combination down and evalu‐
ate it in parts, like so:
let
x
,
y
;
y
=
x
=
3
*
5
;
// original statement
y
=
x
=
15
;
// multiplication expression evaluated
y
=
15
;
// first assignment evaluated; x now has value 15,
// y is still undefined
15
;
// second assignment evaluated; y now has value 15,
// the result is 15, which isn't used or assigned to
// anything, so this final value is simply discarded
The natural question is “How did JavaScript know to execute the expressions in that
order?” That is, it could have reasonably done the assignment
y = x
first, giving
y
the
value
undefined
, and then evaluated the multiplication and the final assignment,
leaving
y
as
undefined
and
x
as
15
. The order in which JavaScript evaluates expres‐
sions is called operator precedence, and we’ll cover it in this chapter.
Most expressions, such as multiplication and assignment, are operator expressions.
That is, a multiplication expression consists of a multiplication operator (the asterisk)
and two operands (the numbers you are trying to multiply, which are themselves
expressions).
The two expressions that are not operator expressions are identifier expressions (vari‐
able and constant names) and literal expressions. These are self-explanatory: a variable
or constant is itself an expression, and a literal is itself an expression. Understanding
this allows you to see how expressions provide homogeneity: if everything that results
80 | Chapter 5: Expressions and Operators