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:
// 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
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
var is a special case we’ll cover later in this chapter).