//Checks a column:
for (i = 0; i < 9; i++) {
if (initial[i][col] == number) {
exists = true;
}
}
Mike: Checking the 3 × 3 boxes was a bit more complicated but basically two nested
for loops did the trick. One p roblem we had to solve was how to set the initial values
of both loop cou nters. We discovered that the indexes of the upper left cell of each
box—that’s where the search should start—are multiples of three. So we only had to
subtract fro m the row ind ex the r emainder after division of the row index by three, and
subtract from the column index the remainder after division of the column index by
three to get the start position. This is the c omplete solution :
//Checks a 3x3 box:
iStart = row - row % 3;
jStart = col - col % 3;
for (i = iStart; i < iStart + 3; i++) {
for (j = jStart; j < jStart + 3; j++) {
if (initial[i][j] == number) {
exists = true;
}
}
}
console.log(exists);
Professor: You did a great job indeed.
Your solution, however, is just a small part of what we have to write in order to get
a complete workin g Sudoku. It’s high time we started thinking about how to pack
individual portion s of code neatly into functio ns to keep things under con trol.
10.2 W ri ti ng Function Definitions
Professor: You already know that a f unction has a name to whic h you appen d a p air
of parentheses in order to call or invoke it. Sometimes you pass one or mor e comm a-
separated arguments to the func tion, wh ic h you do by putting the arguments inside the
parentheses. You also know that a function invocation is an expression, whic h returns
a value like all expressions do. What you do not know is how to define your own
function.
One way of defining a JavaScript function is by using a function expression :
var fun_name = function(par1 , par2, ..., parN ) {
statements
};
188 Meeting 10. Understa nding Functions
A function expression begins with the functio n keyword followed by a p air of paren-
theses with an optional comma-separated parameter list (par1 to parN ). At the end
of a function expression there is a function body, which comprises any number of
JavaScript statements within curly brackets. Note that, unlike statement blocks o f
while and other statements, the function bod y require s curly brackets. They cannot
be omitted even when th e func tion bo dy is composed of only a sing le statement.
Because a function is an object in JavaScript, a function expression in fact returns a
function object, a referenc e to which you usually assign to a variable. In the above
definition, the returned reference is assigned to a variable fun_name . Later, you can
use fun_name to call, or invoke the functio n, which will eectively execute the c ode
placed in its body. Notice a semicolon at the end of the function expression, which is
needed to make a statement out of the expression.
Maria: Can you give us a simple example?
Professor: All right, here’s a really simple one, without any parameters for starters:
var cheer = function() {
var i;
for (i = 0; i < 2; i++) {
document.write("Hip ");
}
document.write("Hooray!");
};
You invoke this fu nction by referring to the variable cheer using an additional pair of
parentheses. Like this:
cheer(); //Writes Hip Hip Hooray!
When you call a function, the main program execution sequence is te mporarily sus-
pended and the code within the func tion bo dy starts to execute. After the function has
terminated, the execution returns to the main program. The following diagram shows
what happens when cheer() is invoked.
cheer();
Main Program
Function
document.write("Hip ");
document.write("Hooray!");
for (i = 0; i < 2; i++) {
}
var i;
Alternatively, you can define a function using a function definition statement:
10.2. Writing Function Definitions 189
function fun_name (par1 , par2 , ..., parN ) {
statements
}
Maria: Are there any dierences between bo th forms of function definition?
Professor: The most important dierence is that you ca nnot call a function before you
define it if you use a function expression. This limitation is, however, rarely an issue
and we will con sistently use func tion expressions to define our function s.
Mike: Are yo u sayin g that it is possible to call a function before it is defin ed when yo u
use a function definition statement? How can you call a function before it is defined?
Professor: In JavaScript te rminology w e say that the fu nction definition statement
is hoisted to the top of the containing script so that it is available to all the code
right from the b egin ning of the script. With a function expression, however, only the
variable declaration is hoisted. The variable initialization code, which represents the
actual function definitio n, is not hoisted.
Mike: I don’t think I quite follow you. Can you give us a n example?
Professor: OK, here ’s a sh ort one. In the following code, the test() function doesn’t
execute because the function is no t yet defined at the time of its invocation:
test(); //Error: undefined is not a function
var test = function() {
document.write("Hello!");
};
If you open the JavaScript Console and examine more closely what is happening,
you get the message “undefined is not a function. Try deleting the second line of
the example an d you get the message “test is not defined. When the second lin e of
the code is present, the test variable is already declared in the first line because its
declaration is hoisted to the top of the containing <script> element. Still, it has
the undefined value because its initialization code—wh ic h is the function definition
proper—is not hoisted.
The situation is identical to the following co de:
var test;
test(); //Error: undefined is not a function
test = function() {
document.write("Hello!");
};
If you instead use a function definition statement, then the invocation of t est() in
the following code will work because the function definition is hoisted:
190 Meeting 10. Understa nding Functions
test(); //Writes Hello!
function test() {
document.write("Hello!");
}
Maria: How do you use fu nction parameters?
Professor: You ca n think of each parameter as a variable used insid e the function
body. When a function is invoked, the p rovided arguments serve as initial values for
these variables.
Maria: If parameters are variables, then I suppose the rules for naming them are the
same as they are for variables.
Professor: That’s true . E xactly the same.
As an example, let’s write a function that takes two arguments and prints the larger of
both to the browser window. H ere is the definition:
var writeLarger = function(x, y) {
document.write(x > y ? x : y);
};
You can invoke this function like this:
writeLarger(5, 13); //Writes 13
When you pass arguments to a function, you mu st be careful that their o rder matc hes
that of the p arameters used in the function definition. In the above example, the a rgu-
ment value 5 is assigned to the x parameter, while the argument value 13 is assigned
to the y parameter. Both param eters are used within the function body to calculate
the value of the conditio nal expression x > y ? x : y, which is then written to the
browser window.
The following dia gram shows how the argument values are transferred to the function
parameter s x and y just before the fu nction body starts to execute.
writeLarger(5, 13);
Main Program
5
13
Function
x
y
document.write(x > y ? x : y);
Do you see anything wrong with this example?
10.2. Writing Function Definitions 191
Maria: Well, no. It works.
Professor: It works all right, but there’s something fundamentally wrong with it.
Imagine a more elaborate example when you write a function that computes and prints
the arithmetic mean of an arra y of numbers. Would such a function be u seful?
Mike: Maybe not so much. For example, if you only want to compute the arithmetic
mean and then do something else with it, n ot print it, then that function would be
completely useless.
Professor: Precisely. O ne of the important programm ing skills is to be able to write
functions that don’t do more th an one otherwise independent task in a single package.
Giving your functions descrip tive names is of great help in managin g that. As soon as
you discover th at a name hints at two dierent and generally independent tasks, make
two functions. For exam ple, the name writeLarger indicates that the function does
two things—it determines w hich value is larger and w rites that value to the browser
window.
Another ad vantage of using descriptive names for fun ctions is that your code will be
more readable and thus easier to maintain.
Mike: I guess that the rules for naming fun ctions are generally the same as they are
for variables.
Professor: That’s right. You may use any legal JavaScript identifier as a function
name so long as it is not a reserved keyword.
Maria: Bu t if a function doesn’t write out what it compute s, then I think it should at
least be able to return the computed value, shouldn’t it?
Professor: Exactly. You can u se the return keyword to accomplish that. The value
of the expression that you associate with retu rn is the return value of the function.
If you don’t use return inside the function b ody—or you u se return without any
expression—then the function returns the undefined value. Note that you can put
return anywhere inside the function body a nd not just at the end—the function will
stop its execution and return as soon as the retur n keyword is reached.
Let’s now split the above writeLarger() function into two independe nt functions.
The first one determines and returns the larger of two arguments, and the other simply
writes out the value of the passed argument:
var larger = function(x, y) {
return x > y ? x : y;
};
var write = function(x) {
document.write(x);
};
The first function returns the value of the expression that app ears afte r the return
keyword. In order to write the larger of two values to the browser window, we may
192 Meeting 10. Understa nding Functions
..................Content has been hidden....................

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