Using the Fluent Interface Pattern to Build Objects in JavaScript

Nick Scialli April 26, 2020🚀 1 minute read

There are many ways to create new JavaScript objects. In this post, we’ll use the fluent interface pattern! In the fluent interface pattern, we use classes with defined methods to add attributes to our object.

In the following example, we create a PersonBuilder class. In the constructor, we create an empty person property. Then, we have some additional methods called withName and withAge that allow us to give our person a name and age, respectively.

Finally, we have a build method. This just returns our person object, signifying that we’re done building.

class PersonBuilder {
  constructor() {
    this.person = {};
  withName(name) {
    this.person.name = name;
    return this;
  withAge(age) {
    this.person.age = age;
    return this;
  build() {
    return this.person;

Note that we return this in the withName and withAge methods—this returns the current instance, allowing us to continue to chain methods.

The implementation of our class ends up being something like this:

const person = new PersonBuilder().withName('Daffodil').withAge(25).build();
// { name: "Daffodil", age: 25 }

And that’s it, we now have a person object!

Why Build Objects This Way?

The fluent interface pattern can definitely be verbose, but one nice thing about it is that it makes it pretty hard to set an incorrect property on your object—you can only set object props by using the methods on your class. This can be especially handy if your object has a lot of properties, or if you need a handy way to generate a bunch of different objects to a specification (e.g., for test case generation).

Did this post help you?

I'd appreciate your feedback so I can make my blog posts more helpful. Did this post help you learn something or fix an issue you were having?

If you'd like to support this blog by buying me a coffee I'd really appreciate it!

Nick Scialli

Nick Scialli is a software engineer at the U.S. Digital Service.