LEARNING JAVASCRIPT - Trang 109

let

x

=

3

,

y

;

x

+=

y

=

6

*

5

/

2

;

// we'll take this in order of precedence, putting parentheses around
// the next operation:
//
// multiplication and division (precedence level 14, left to right):
// x += y = (6*5)/2
// x += y = (30/2)
// x += y = 15
// assignment (precedence level 3, right to left):
// x += (y = 15)
// x += 15 (y now has value 15)
// 18 (x now has value 18)

Understanding operator precedence may seem daunting at first, but it quickly

becomes second nature.

Comparison Operators

Comparison operators, as the name implies, are used to compare two different values.

Broadly speaking, there are three types of comparison operator: strict equality,

abstract (or loose) equality, and relational. (We don’t consider inequality as a different

type: inequality is simply “not equality,” even though it has its own operator for con‐

venience.)
The most difficult distinction for beginners to understand is the difference between

strict equality and abstract equality. We’ll start with strict equality because I recom‐

mend you generally prefer strict equality. Two values are considered strictly equal if

they refer to the same object, or if they are the same type and have the same value (for

primitive types). The advantage of strict equality is that the rules are very simple and

straightforward, making it less prone to bugs and misunderstandings. To determine if

values are strictly equal, use the

===

operator or its opposite, the not strictly equal

operator (

!==

). Before we see some examples, let’s consider the abstract equality

operator.
Two values are considered abstractly equal if they refer to the same object (so far, so

good) or if they can be coerced into having the same value. It’s this second part that

causes so much trouble and confusion. Sometimes this is a helpful property. For

example, if you want to know if the number

33

and the string

"33"

are equal, the

abstract equality operator will says yes, but the strict equality operator will say no

(because they aren’t the same type). While this may make abstract equality seem con‐

venient, you are getting a lot of undesirable behavior along with this convenience. For

this reason, I recommend converting strings into numbers early, so you can compare

them with the strict equality operator instead. The abstract equality operator is

==

and the abstract inequality operator is

!=

. If you want more information about the

Comparison Operators | 85

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.