• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 7. Functions > What Is a Function?

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 function 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 modules 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 independent of your program and not executed 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.”


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint