In this tutorial, we’ll discuss 7 Best Practices to Write More Robust JavaScript

1. Use factory functions

If you don’t know what a factory function is, it’s simply a function (that isn’t a class or constructor) that returns an object. This simple concept allows us to take advantage of JavaScript and its features to create powerful robust applications.

It’s important to know that they’re no longer factory functions when they’re called with the _new_ keyword.

Why factory functions?

Factory functions can be used to easily produce instances of objects without having anything to do with classes or the new keyword.

What it essentially means is that they ultimately become treated as just functions, which means they can be used to compose objects, functions, and even promises. This means you can mix and match factory functions together to create an enhanced factory function, then continue composing with other functions or objects to create even further enhanced ones. The possibilities are endless.

When we take that into consideration and combine it with good code practices, it really begins to shine.

Here is a simple example of a factory function:

function createFrog(name) {
  const children = []

  return {
    addChild(frog) {
      children.push(frog)
    },
  }
}

const mikeTheFrog = createFrog('mike')

When you’ve used factory functions enough, you begin to realize that compared to its class constructor counterpart, it promotes stronger reusability. This results in less code, an easier time refactoring since factory functions ultimately return arbitrary objects, and an easier time managing one code to another.

#javascript #programming

7 Best Practices to Write More Robust JavaScript
19.15 GEEK