LEARNING JAVASCRIPT - Trang 58

let

currentTempC

=

22

;

// degrees Celsius

The let keyword is new in ES6; prior to ES6, the only option was

the var keyword, which we will discuss in

Chapter 7

.

This statement does two things: it declares (creates) the variable

currentTempC

and

assigns it an initial value. We can change the value of

currentTempC

at any time:

currentTempC

=

22.5

;

Note that we don’t use

let

again;

let

specifically declares a variable, and you can only

do it once.

With numbers, there’s no way to associate units with the value.

That is, there’s no language feature that allows us to say that
currentTempC

is in degrees Celsius, thereby producing an error if

we assign a value in degrees Fahrenheit. For this reason, I chose to

add “C” to the variable name to make it clear that the units are

degrees Celsius. The language can’t enforce this, but it’s a form of

documentation that prevents casual mistakes.

When you declare a variable, you don’t have to provide it with an initial value. If you

don’t, it implicitly gets a special value,

undefined

:

let

targetTempC

;

// equivalent to "let targetTempC = undefined";

You can also declare multiple variables with the same

let

statement:

let

targetTempC

,

room1

=

"conference_room_a"

,

room2

=

"lobby"

;

In this example, we’ve declared three variables:

targetTempC

isn’t initialized with a

variable, so it implicitly has the value

undefined

;

room1

is declared with an initial

value of

"conference_room_a"

; and

room2

is declared with an initial value of

"lobby"

.

room1

and

room2

are examples of string (text) variables.

A constant (new in ES6) also holds a value, but unlike a variable, can’t be changed

after initialization. Let’s use a constant to express a comfortable room temperature

and a maximum temp (

const

can also declare multiple constants):

const

ROOM_TEMP_C

=

21.5

,

MAX_TEMP_C

=

30

;

It is conventional (but not required) for constants that refer to a specific number or

string to be named with all uppercase letters and underscores. This makes them easy

to spot in your code, and is a visual cue that you shouldn’t try to change their value.

34 | Chapter 3: Literals, Variables, Constants, and Data Types

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.