Builder pattern in JavaScript without classes

Design patterns are a vital part of software development. They describe common problems and solutions to them. One such pattern is the builder pattern. As Wikipedia puts it, it is “a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming”. However, I am here to show you that it does not only apply to object-oriented languages and can be achieved in JavaScript without classes.

How does the builder pattern work?

The purpose of the builder pattern is to streamline the object creation process. It is different from the factory pattern: the builder pattern is useful when the creation process is complex and requires an arbitrary number of inputs. One famous example is the StringBuilder class in Java, that is used to build strings (duh):

Given the OOP nature of the builder pattern, you may think that to implement it you have to use classes. But I am here to prove you wrong: this pattern is perfectly valid for functional languages such as JavaScript, thanks to the prototypical delegation and this binding.

Implementing the builder pattern in JavaScript

To implement the builder pattern, we are going to use the constructor functions, the new keyword and this binding. Note that these features have nothing to do with classes, their behaviour is not related to classes and they were introduced way before classes were. As a use-case for the builder pattern, imagine that you have to perform a lot of common HTTP requests to the same server with the same header and would like to simplify the API. Observe this code:

First, note the ClientBuilder function. It returns an object that holds all the building logic. It exposes functions forBaseUrl, withHeaders, usingFetch, usingAxios, and, build. You use these functions to specify the desired behaviour and then use build to get the complete client. The Client function is a constructor function, that accepts baseUrl, headers and executor, binds it via this and exposes functions post and get. You will then use these functions like this:

This wraps up our discussion about the builder pattern in JavaScript, hope you found it useful. Let me know what other design patterns you want me to cover!

Get new content delivered to your mailbox:

leave a comment