LEARNING JAVASCRIPT - Trang 141

CHAPTER 7

Scope

Scope determines when and where variables, constants, and arguments are considered

to be defined. We’ve already had some exposure to scope: we know that the argu‐

ments of a function exist only in the body of the function. Consider the following:

function

f

(

x

) {

return

x

+

3

;

}

f

(

5

);

// 8

x

;

// ReferenceError: x is not defined

We know that

x

lived very briefly (otherwise, how would it have successfully calcula‐

ted

x + 3

?), but we can see that outside of the function body, it’s as if

x

doesn’t exist.

Thus, we say the scope of

x

is the function

f

.

When we say that the scope of a variable is a given function, we must remember that

the formal arguments in the function body don’t exist until the function is called

(thereby becoming actual arguments). A function may be called multiple times: each

time the function is called, its arguments come into existence, and then go out of

scope when the function returns.
We have also taken it for granted that variables and constants do not exist before we

create them. That is, they aren’t in scope until we declare them with

let

or

const

(

var

is a special case we’ll cover later in this chapter).

In some languages, there’s an explicit distinction between declara‐

tion and definition. Typically, declaring a variable means that you

are announcing its existence by giving it an identifier. Definition,

on the other hand, usually means declaring it and giving it a value.

In JavaScript, the two terms are interchangeable, as all variables are

given a value when they’re declared (if not explicitly, they implicitly

get the value undefined).

117

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.