LEARNING JAVASCRIPT - Trang 107

on fractional operands as well. For example,

10 % 3.6

will be

3

(3.6 goes into 10

twice, with 2.8 left over).
The increment operator (

++

) is effectively an assignment and addition operator all

rolled into one. Likewise, the decrement operator (

--

) is an assignment and subtrac‐

tion operator. They are useful shortcuts, but should be used with caution: if you bury

one of these deep in an expression, it might be hard to see the “side effect” (the

change in a variable). Understanding the difference between the

prefix and postfix

operators is important as well. The prefix version modifies the variable and then eval‐

uates to the new value; the postfix operator modifies the variable and then evaluates

to the value before modification. See if you can predict what the following expressions

evaluate to (hint: increment and decrement operators are evaluated before addition,

and we evaluate from left to right in this example):

let

x

=

2

;

const

r1

=

x

++

+

x

++

;

const

r2

=

++

x

+

++

x

;

const

r3

=

x

++

+

++

x

;

const

r4

=

++

x

+

x

++

;

let

y

=

10

;

const

r5

=

y

--

+

y

--

;

const

r6

=

--

y

+

--

y

;

const

r7

=

y

--

+

--

y

;

const

r8

=

--

y

+

y

--

;

Go ahead and run this example in a JavaScript console; see if you can anticipate what

r1

through

r8

will be, and what the value of

x

and

y

is at each step. If you have prob‐

lems with this exercise, try writing the problem down on a piece of paper, and adding

parentheses according to the order of operations, then doing each operation in order.

For example:

let

x

=

2

;

const

r1

=

x

++

+

x

++

;

// ((x++) + (x++))
// ( 2 + (x++)) eval left to right; x now has value 3
// ( 2 + 3 ) x now has value 4
// 5 result is 5; x has value 4

const

r2

=

++

x

+

++

x

;

// ((++x) + (++x))
// ( 5 + (++x)) eval left to right; x now has value 5
// ( 5 + 6 ) x now has value 6
// 11 result is 11; x has value 6

const

r3

=

x

++

+

++

x

;

// ((x++) + (++x))
// ( 6 + (++x)) eval left to right; x now has value 7
// ( 6 + 8 ) x now has value 8
// 14 result is 14; x has value 8
//
// ... and so on

Arithmetic Operators | 83