LEARNING JAVASCRIPT - Trang 119

For example, consider Unix-style file permissions: read, write, and execute. A given

user can have any combination of these three settings, making them ideal for flags.

Because we have three flags, we need three bits to store the information:

const

FLAG_READ

1

// 0b001

const

FLAG_WRITE

2

// 0b010

const

FLAG_EXECUTE

4

// 0b100

With bitwise operators, we can combine, toggle, and detect individual flags in a single

numeric value:

let

p

=

FLAG_READ

|

FLAG_WRITE

;

// 0b011

let

hasWrite

=

p

&

FLAG_WRITE

;

// 0b010 - truthy

let

hasExecute

=

p

&

FLAG_EXECUTE

;

// 0b000 - falsy

p

=

p

^

FLAG_WRITE

;

// 0b001 -- toggle write flag (now off)

p

=

p

^

FLAG_WRITE

;

// 0b011 -- toggle write flag (now on)

// we can even determine multiple flags in one expression:

const

hasReadAndExecute

=

p

&

(

FLAG_READ

|

FLAG_EXECUTE

);

Note that for

hasReadAndExecute

we had to use the grouping operator; AND has a

higher precedence than OR, so we had to force the OR to evaluate before the AND.

typeof Operator

The

typeof

operator returns a string representing the type of its operand. Unfortu‐

nately, this operator doesn’t exactly map to the seven data types in JavaScript (

unde

fined

,

null

, boolean, number, string, symbol, and object), which has caused no end

of criticism and confusion.
The

typeof

operator has one quirk that’s usually referred to as a bug:

typeof null

returns

"object"

.

null

is not, of course, an object (it is a primitive). The reasons are

historical and not particularly interesting, and it has been suggested many times that

it be fixed, but too much existing code is already built on this behavior, so it’s now

immortalized in the language specification.

typeof

is also often criticized for not being able to distinguish arrays and nonarray

objects. It correctly identifies functions (which are also special types of objects), but

typeof []

results in

"object"

.

Table 5-8

lists the possible return values of

typeof

.

Grouping Operator | 95

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.