Chapter 4. Functions: code on demand

 

This chapter covers

  • Organizing instructions with functions
  • Defining a function—specifying code to be executed on demand
  • Calling a function—executing code on demand
  • Reducing repetition in code
  • Making programs easier to read and update

One of the main themes of Get Programming with JavaScript is managing complexity through good organization. In chapter 2, you stored information in variables and saw how choosing good names for those variables helps you understand their purpose in a program. In chapter 3, you grouped variables as properties of objects. You can focus on objects as a whole or drill down into the details when needed. In this chapter you take a look at another important method for organizing code and avoiding repetition, the function.

4.1. Noticing repetition

As the programs you write become longer and more complex, you find yourself repeating similar sections of code with only slight differences. Common tasks, like displaying text, animating an image, or saving to a database, may need to be performed often. You need to notice these recurring bits of code; they’re prime function fodder.

A function is a way of writing code once but using it many times. Section 4.2 looks at how to create functions. This section explores a couple of examples of JavaScript repeated.

4.1.1. Displaying object properties as text

4.2. Defining and calling functions

4.3. Reducing repetition

4.4. Making code easier to read and update

4.5. The Crypt—displaying player information

4.6. Summary

sitemap