Chapter 2. Functions
Functions are the building blocks of applications. They are particularly important in JavaScript because JavaScript supports first-class functions, functions as objects, runtime function definition, and so on. JavaScript’s features allow you to use functions in ways that you may not be familiar with. It’s important to have a thorough understanding of how functions work in JavaScript so you can leverage them to full advantage in your applications. By the end of this chapter, you should see functions in a whole new light.
Here are some guidelines that will help you write better functions:
- Don’t Repeat Yourself (DRY)
Good programmers are both lazy and very productive. They express a lot of functionality in very little code. Once you have established a pattern for something that gets repeated again in the code, it’s time to write a function, object, or module that encapsulates that pattern so that it can be easily reused.
Doing so also quarantines that functionality to a single spot in the code base, so that if you later find something wrong with the code or the algorithm, you only have to fix it in one place.
Writing a reusable function also forces you to isolate the pattern from the problem, which helps you keep related functionality grouped together.
- Do One Thing (DOT)
Each function should do only one thing, and do that one thing as well as it can. Following this principle will make your function more reusable, more readable, and easier to debug.
- Keep It Simple Stupid ...