LEARNING JAVASCRIPT - Trang 68

const

multiline

=

`line1

line2
line3`

;

For this reason, I avoid multiline string syntax: it forces me to either abandon inden‐

tation that makes code easier to read, or include whitespace in my multiline strings

that I may not want. If I do want to break strings up over multiple lines of source

code, I usually use string concatenation:

const

multiline

=

"line1\n"

+

"line2\n"

+

"line3"

;

This allows me to indent my code in an easy-to-read fashion, and get the string I

want. Note that you can mix and match types of strings in string concatenation:

const

multiline

=

'Current temperature:\n'

+

`\t

${

currentTemp

}

\u00b0C\n`

+

"Don't worry...the heat is on!"

;

Numbers as Strings

If you put a number in quotation marks, it’s not a number—it’s a string. That said,

JavaScript will automatically convert strings that contain numbers to numbers as nec‐

essary. When and how this happens can be very confusing, as we will discuss in

Chapter 5

. Here’s an example that illustrates when this conversion happens, and when

it doesn’t:

const

result1

=

3

+

'30'

;

// 3 is converted to a string; result is string '330'

const

result2

=

3

*

'30'

;

// '30' is converted to a number; result is numeric 90

As a rule of thumb, when you want to use numbers, use numbers (that is, leave off the

quotes), and when you want to use strings, use strings. The gray area is when you’re

accepting user input, which almost always comes as a string, leaving it up to you to

convert to a number where appropriate. Later in this chapter, we will discuss techni‐

ques for converting among data types.

Booleans

Booleans are value types that have only two possible values:

true

and

false

. Some

languages (like C) use numbers instead of booleans: 0 is

false

and every other num‐

ber is

true

. JavaScript has a similar mechanism, allowing any value (not just num‐

bers) to be considered “truthy” or “falsy,” which we’ll discuss further in

Chapter 5

.

Be careful not to use quotation marks when you intend to use a boolean. In particu‐

lar, a lot of people get tripped up by the fact that the string

"false"

is actually truthy!

Here’s the proper way to express boolean literals:

44 | 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.