O'Reilly logo

Learning JavaScript, 3rd Edition by Todd Brown

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 arguments 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 calculated 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).

Note

In some languages, there’s an explicit distinction between declaration 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required