How to Reduce Work with Custom Functions in JavaScript - dummies

How to Reduce Work with Custom Functions in JavaScript

By John Paul Mueller

Using custom functions helps reduce the work you must perform in JavaScript when creating an application and integrating with HTML. Functions help you reduce your workload in the following ways:

  • Code reuse: By encapsulating a specific task, you can reuse it as often as needed.

  • Ease of understanding: Using functions creates a number of black boxes that reduce the complexity of the programming task.

  • Error trapping: It’s usually easier to trap erroneous output from an entire function than it is to check each step within that function for potential problems.

  • Debugging: When you know that a problem in your application lies in a certain location, it’s helpful to get to that point in the application as quickly as possible by bypassing the code you know works.

  • Ease of coding changes: Cutting and pasting the same code in multiple locations makes it nearly impossible to make changes consistently or completely.

There are other reasons to use functions, but the preceding are the reasons that most developers cite for using them. When you consider the issues that functions resolve, it becomes obvious that they’re incredibly useful.

Unfortunately, some developers go overboard and use too many functions, making it harder to understand the code or follow what the developer intends to do. Creating useful functions that actually reduce your workload means thinking through the application process carefully.

The following guidelines help you determine when code should go into a separate function:

  • Create functions that perform a complete task rather than only part of a task.

  • Consider creating a new function when the code you’ve written takes up more than a single page — a function is easier to understand when you can see all of the code on a single screen.

  • Define new functions with code reusability in mind. Functions should provide enough flexibility to serve a number of callers.

  • Think of functions as mini-apps — the function should perform one task really well rather than trying to perform multiple tasks poorly.

Never create a new function that replicates the behavior of an existing function or a built-in function. It pays to verify that the function is actually needed before you spend time writing it. Reinventing the wheel will almost certainly cost you time, and you may not even get a superior function for your efforts.