LEARNING JAVASCRIPT - Trang 59

Variables or Constants: Which to Use?

In general, you should prefer constants over variables. You’ll find that more often

than not you want a handy name for some piece of data, but you don’t need its value

to change. The advantage of using constants is that it makes it harder to accidentally

change the value of something that shouldn’t be changed. For example, if you’re

working on a part of your program that performs some kind of action on a user, you

might have a variable called

user

. If you’re dealing with only one user, it would prob‐

ably indicate an error in your code if the value of

user

changed. If you were working

with two users, you might call them

user1

and

user2

, instead of simply reusing a sin‐

gle variable

user

.

So your rule of thumb should be to use a constant; if you find you have a legitimate

need to change the value of the constant, you can always change it to a variable.
There is one situation in which you will always want to use variables instead of con‐

stants: variables used in loop control (which we’ll learn about in

Chapter 4

). Other

situations where you might want to use variables are when the value of something is

naturally changing over time (such as

targetTempC

or

currentTemp

in this chapter).

If you get in the habit of preferring constants, however, you might be surprised by

how seldom you really need a variable.
In the examples in this book, I have tried to use constants instead of variables when‐

ever possible.

Identifier Names

Variable and constant names (as well as function names, which we’ll cover in

Chap‐

ter 6

) are called identifiers, and they have naming rules:

• Identifiers must start with a letter, dollar sign ($), or underscore (_).
• Identifiers consist of letters, numbers, the dollar sign ($), and underscore (_).
• Unicode characters are allowed (for example, π or ö).
• Identifiers cannot be a reserved word (see

Appendix A

).

Note that the dollar sign is not a special character the way it is in some other lan‐

guages: it’s simply another character you can use in identifier names (many libraries,

such as jQuery, have taken advantage of this, and used the dollar sign by itself as an

identifier).
Reserved words are words that JavaScript might confuse with part of the language.

For example, you can’t have a variable called

let

.

There’s no single convention for JavaScript identifiers, but the two most common are:

Variables or Constants: Which to Use? | 35

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.