Maria: So I can call the above f unction that does somethin g useful like this:
funcArray[0]();
Professor: Pre cisely.
Armed with that knowledge, we are now able to finish our lucky lottery number gen-
erator, which uses the sort() meth od of the Array object to sort the numbers. By
default, sort() orders array elements alp habetically, which isn’t exactly what we
want in ou r example. It is actua lly possible to sort array elements using an arb itrary
compariso n criterion, which is supp lied as an argume nt to the sort() method. The
argument is simply a reference to a function implementing the com parison criterion.
The function must take two arguments, arg1 and arg2 , and return one of the follow-
ing:
A value less than zero, if arg1 should appear before arg2 in the sorted array.
Zero, if both arguments are equal in view of this sort and their relative p ositions
don’t ma tter.
A value greater than zero, if arg1 should appear after arg2 in the sorte d array.
This is a solution that will work fo r our lottery generator:
var order = function(x, y) { return x - y; };
//...
drawnNumbersList.sort(order);
If you’re puzzled how this might work, imagine that so rt() uses the passed reference
to call our criterion function many time s, each time co mparing two elements of the
array and switching their positions when necessary. The scheme defining the fashion
in which elements are selected for a comparison is described by a sorting algorithm ,
which you don’t need to know in order to be able to use sort().
Mike: It’s beginning to worr y me that with several function de finitions in my program
I might accidentally choose a parameter name that already exists as a variable else-
where in m y code. That could easily hap pen as the size of my code grows, couldn’t
it?
Professor: Lu ckily, you are not the only one who has thought of that, so there ex-
ist so -called scoping ru le s to help you manage th e n ame conflicts like the one you
hypothesized.
10.4 Variable Scope
Professor: You know, not every variable is accessible anywhere in your program
source code . The scope of a variable specifies pr ecisely in wh ic h parts of the code
the variable is defined . If you declare a variable outside of any function, then that is
a global variable, which has global scope. Global variables are accessible anywhere
196 Meeting 10. Understa nding Functions
in your program. On the other hand, if you declare a variable within a function body,
then you declare a local variable, which has local scope. This is also called function
scope in JavaScript because such a variable is defined only within the function bo dy
in which it is declared. Note that func tion parameters act as local variables and are
thus only accessible within the function body.
Now, a question ar ises: w hat if there are two variables, one local and the other g lobal,
using the same name? According to the just-mentio ned rules, both should be a cces-
sible within the function body in which the loc al variable is declared. To solve the
conflict, th ere’s an additional rule which say s that a local variable takes precedence
over a global variable with the same name. If you hence declare a local variable, or
a func tion parameter, for that matter, choosing the same name as th at of some global
variable, then you hide that global variable from the code within the func tion body.
The next short example illuminates the whole idea:
var scope = "global";
var f1 = function() { var scope = "local"; return scope; };
var f2 = function() { return scope; };
console.log(scope); //Writes global
console.log(f1()); //Writes local
console.log(f2()); //Writes global
There are two variables named scope in the example. The first one is declared outside
of any of the functions and is hence a glo bal variable. The second one is declared
within the body of the f1() function, which makes it a local variable of that function.
The first call to console.log() takes place outside of any function and can th erefore
only access the global scope variable. The seco nd call to console.log() writes
out wh atever f1 () returns, which is the value of its local scope variable. Namely,
f1() ha s no access to the global s cope variable, which is hidden by the local variable
with the same name. Finally, the thir d c all to console.log() writes out what f2()
returns, which is the value of the global sco pe variable since this is the only variable
accessible within the b ody of f2().
To help you better visualize the situation, heres a graphical representation of the
scopes of the two scope variables.
global
var scope = "global";
f1
var scope = "local";
f2
The white area indicates the scope of the local scope variable, whereas the scope of
the glo bal scope variable is shaded gray.
Mike: I sh ould probably have asked this before, but are the re any limitations on where
you can declare variables? You a lways declare them a t the beginning of your code or
a f unction body, altho ugh I think I saw them declared elsewhere as well.
10.4. Variable Scope 197
Professor: You can in fact declare a variable anywhere you want. In any case the
declaration will be hoisted to the top of the containing script or the function body for
local variables. The variable initialization, however, is not hoisted.
Maria: That’s the same as it is with a function expression, which is also not hoisted.
Professor: Absolutely.
Let me show you some examples. Con sid er th e following code:
var scope = "global";
var f1 = function() {
var tmp = scope;
var scope = "local";
return tmp;
};
It lo oks like the local scope variable has not y et been declared at the time when we
assign it to the tmp variable, and that the global scop e variable is visible instead. That
is, however, not the case. The local scope variable declaration is hoisted to the top of
the f1() function definition so that the variable is alre ady declared at the time when
the var tm p = scope; statement is executed. On the other hand, the initialization
of the local s cope variable takes place exactly where it is written—in th e second lin e
of the function body. That means that th e local scope variable has the un defined
value at the time we assign it to the tmp variable.
Maria: So the function will return undefined?
Professor: Pre cisely. In fact, the above cod e is equivalent to this one:
var scope = "global";
var f1 = function() {
var scope;
var tmp = scope;
scope = "local";
return tmp;
};
That’s why I always put variable declarations at the beginning of their scope. That
way, what is actually going on is more evident.
Let’s examine this second example in the DevTools. You should add an f1() function
invocation at the en d of the code so the function will execute, and set a breakpoint
at the first line of the function body. After that, you reload the page and expand the
Scope Variables menu item at the right side of the DevTools window. This is what
you should see.
198 Meeting 10. Understa nding Functions
Under the Local item you’ll find both local variables, scope and tmp o f the current
local scope. T he current scope is tha t of f 1() because that’s where the debugger has
paused. You can also see the this keyword, which you’ll learn about next week.
Below, you can see the
Global section, under which there’s quite a bit of stu listed.
There is, for example, the familiar Infinity global variable, and if you scroll fu rther
down, you’ll find other recog nizable items like Array, D ate, Document , NaN, and
so forth. These are all globally accessible variables and functions. They are, techni-
cally speaking, all member s of a global object, w hich is called Window in client side
JavaScript. T hat’s why ther es “Window” written at the right of the
Global item. Don’t
worry about all that, though. The important thing is that you can also find our globa l
scope variable on the list of global identifiers. As you can ob serve on the r ight side
of the DevTools on the next screenshot, its value is "global", just like it should be .
If you expand the Watch Expressions menu item and add the scope variable to the
list of watch expressions, you’ll see that the variable has the undef ined value. That’s
because we’re currently inside the local scope of f1 () and
Watch Expressions uses
only variables that are accessible within the current scope.
10.4. Variable Scope 199
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.47.97