LEARNING JAVASCRIPT - Trang 106

Operator Description

Example

--

Pre-decrement

--x // decrements x by one, and evaluates to the new
value

--

Post-decrement

x-- // decrements x by one, and evaluates to value of x
before the decrement

Remember that all numbers in JavaScript are doubles, meaning that if you perform an

arithmetic operation on an integer (such as

3/2

), the result will be a decimal number

(1.5).
Subtraction and unary negation both use the same symbol (the minus sign), so how

does JavaScript know how to tell them apart? The answer to this question is complex

and beyond the scope of the book. What’s important to know is that unary negation is

evaluated before subtraction:

const

x

=

5

;

const

y

=

3

-

-

x

;

// y is 8

The same thing applies for unary plus. Unary plus is not an operator you see used

very often. When it is, it is usually to force a string to be converted to a number, or to

align values when some are negated:

const

s

=

"5"

;

const

y

=

3

+

+

s

;

// y is 8; without the unary plus,

// it would be the result of string

// concatenation: "35"

// using unnecessary unary pluses so that expressions line up

const

x1

=

0

,

x2

=

3

,

x3

=

-

1.5

,

x4

=

-

6.33

;

const

p1

=

-

x1

*

1

;

const

p2

=

+

x2

*

2

;

const

p3

=

+

x3

*

3

;

const

p3

=

-

x4

*

4

;

Note that in these examples, I specifically used variables in conjunction with unary

negation and unary plus. That’s because if you use them with numeric literals, the

minus sign actually becomes part of the numeric literal, and is therefore technically

not an operator.
The remainder operator returns the remainder after division. If you have the expres‐

sion

x % y

, the result will be the remainder when dividing the dividend (

x

) by the

divisor (

y

). For example,

10 % 3

will be

1

(3 goes into 10 three times, with 1 left over).

Note that for negative numbers, the result takes on the sign of the dividend, not the

divisor, preventing this operator from being a true modulo operator. While the

remainder operator is usually only used on integer operands, in JavaScript, it works

82 | Chapter 5: Expressions and Operators

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.