HTML and CSS Reference
In-Depth Information
7
Functions
7.1 What Is a Function?
A pocket calculator performs certain functions. You push the buttons, send information
to the calculator, it performs a calculation, and sends back the results. You don't care
about what transpires inside the calculator, you just want the results. That's what a func-
tion does. Functions are self-contained units of a program designed to accomplish a
specified task such as calculating mortgage payments, displaying random images, or
checking for valid input. They can be used over and over again and thus save you from
repetitious programming. They are also used to break up a program into smaller mod-
ules to keep it better organized and easier to maintain. JavaScript has a large number of
its own built-in functions, and now you can create your own.
By definition, a function is a block of statements that not only performs some task,
but also returns a value. A function is an independent part of your program and not exe-
cuted until called. A function is often referred to as a “black box.” It's like the pocket
calculator: Information goes into the black box (or calculator) as input and the action
or value returned from the box is its output. What goes on inside the box is transparent
to the user. The programmer who writes the function is the only one who cares about
those details. When you use document.write() , you send something like a string of text
to the function, and it sends some text back to the browser. You don't care how it does
its job, you just expect it to work. If you send bad input, you get back bad output or
maybe nothing, hence the expression “Garbage in, garbage out.”
Functions are like miniscripts. They contain JavaScript statements that behave as a
single command and can be called repeatedly throughout a program without rewriting
the code.
The terms “function” and “method” are often used interchangeably. A method refers
to a function that is used with JavaScript objects (covered in Chapter 8, “Objects”). A
function, as used in this chapter, is a stand-alone block of statements, independent of
the program until invoked by a caller.
143
 
 
 
Search WWH ::




Custom Search