Lesson 1: Introducing JavaScript CHAPTER 3 77
FIGURE 3-3 he confirm window presents a message and OK and Cancel buttonsT
These built-in functions, and any functions you write, can be overwritten very easily
because the function name is a variable. Consider the following scenario, in which a different
function is assigned to the prompt function:
prompt = function(){
return 'hello again';
};
This code replaces the behavior of the prompt function with a function that always returns
the string, ‘hello again’. The function name is represented by a variable, and you can change
its value dynamically. This is the same for function declarations and function expressions.
Scoping variables
Scoping is the context within a computer program in which a variable name is valid and can
be used to access the variable. Outside the scope of a variable name, the variable’s value
might still be stored and might even be accessible in some way, but the name cannot access
the value.
In JavaScript, there are essentially two scopes, global and local. A variable with a global
scope is accessible from anywhere in the program. A variable with a local scope is accessible
only from within the function in which the variable is defined, so you can think of local scope
as being function scope.
The fact that local scope is limited to a function is very different from many other lan-
guages, in which a new local scope is created for each set of curly braces. This means that in
many other languages, conditional and looping statements that have curly braces also start
a new local context. This is not the case for JavaScript, in which the only local scope is at the
function. Variables that are declared anywhere inside the function will have a local function
scope. To avoid confusion, you should declare all function variables at the top of the function.
NOTE BE CAREFUL NOT TO CREATE GLOBAL VARIABLES IMPLICITLY
If you do not use the var keyword when you declare a variable, the variable is automatically
created, but it will have a global scope. Consider the following code example:
totalCost = 3 * 21.15;
tax = totalCost * 1.05;
Key
Te rms