JavaScript and TypeScript course ยท Module 5: Advanced JavaScript
The Builder Pattern in JavaScript
In this lesson6
In Jurassic Park, creating a new dinosaur is a complex process. Dr. Henry Wu can't just dump all the parameters into one constructor - genetic sequence, diet, habitat, danger level, temperature requirements... dozens of parameters! Fortunately there's the Builder pattern - an elegant way to construct complex objects step by step.
The Problem: Too Many Parameters
Imagine a dinosaur constructor that takes eleven arguments in a rigid order and without any names:
// Constructor with many parameters - unreadable and error-prone
const dino = new Dinosaur(
"Rexy", // name
"Tyrannosaurus", // species
"carnivore", // diet
8, // age
12000, // weight
"Sector A", // habitat
10, // dangerLevel
true, // isActive
38, // optimalTemp
null, // mate
["hunt", "roar"] // abilities
);
// Which parameter is which? Easy to mix up the order!We recognize the arguments by position only. Swapping the age with the danger level passes without an error, because both are numbers, and the mistake only comes to light in the enclosure. A bare true or null in the middle of the list tells the person reading the code nothing.
The Builder Pattern - Solution
Builder lets you construct an object step by step with a readable API based on method chaining. The required data, the name and species, go to the constructor, and every optional trait is set by a separate method with a clear name:
class DinosaurBuilder {
constructor(name, species) {
// Required parameters in constructor
this.dinosaur = {
name,
species,
abilities: []
};
}
// Each method sets a property and returns this (the builder)
setDiet(diet) {
this.dinosaur.diet = diet;
return this; // Critical! Returns the builder, enabling chaining
}
setAge(age) {
this.dinosaur.age = age;
return this;
}
setWeight(weight) {
this.dinosaur.weight = weight;
return this;
}
setHabitat(habitat) {
this.dinosaur.habitat = habitat;
return this;
}
setDangerLevel(level) {
this.dinosaur.dangerLevel = level;
return this;
}
setActive(isActive) {
this.dinosaur.isActive = isActive;
return this;
}
setOptimalTemperature(temp) {
this.dinosaur.optimalTemp = temp;
return this;
}
addAbility(ability) {
this.dinosaur.abilities.push(ability);
return this;
}
// build() creates the final object
build() {
// Validation before building
if (!this.dinosaur.diet) {
throw new Error("Diet is required!");
}
return { ...this.dinosaur };
}
}The heart of the pattern is the return this line: each method changes one property and hands back the same builder, so you can call the next method on the result right away. The build() method finishes the job - it validates the data first and then returns a copy of the collected properties.
This is what usage looks like. Every link of the chain says what it sets, so the code reads like a lab protocol:
// Usage - readable and self-documenting
const rexy = new DinosaurBuilder("Rexy", "Tyrannosaurus")
.setDiet("carnivore")
.setAge(8)
.setWeight(12000)
.setHabitat("Sector A")
.setDangerLevel(10)
.setActive(true)
.setOptimalTemperature(38)
.addAbility("hunt")
.addAbility("roar")
.build();
console.log(rexy);
// { name: "Rexy", species: "Tyrannosaurus", abilities: ["hunt", "roar"],
// diet: "carnivore", age: 8, weight: 12000, habitat: "Sector A",
// dangerLevel: 10, isActive: true, optimalTemp: 38 }new DinosaurBuilder(...) always comes first, then the setter methods in any order, and build() at the very end, because it returns the finished object, not the builder. Note: the spread in build() makes a shallow copy, so the abilities array is shared between the builder and the finished dinosaur.
Fluent API - Method Chaining in Practice
The key to the Builder pattern is the Fluent API - each method returns this, allowing calls to be chained. The same trick works great for queries to the dinosaur database. First, the query builder itself:
// Fluent API for building dinosaur queries
class DinoQueryBuilder {
constructor() {
this.query = {
filters: {},
sort: null,
limit: 100,
offset: 0
};
}
whereSpecies(species) {
this.query.filters.species = species;
return this;
}
whereDiet(diet) {
this.query.filters.diet = diet;
return this;
}
whereDangerAbove(level) {
this.query.filters.minDanger = level;
return this;
}
whereActive(isActive = true) {
this.query.filters.isActive = isActive;
return this;
}
sortBy(field, direction = "asc") {
this.query.sort = { field, direction };
return this;
}
limitTo(count) {
this.query.limit = count;
return this;
}
skip(count) {
this.query.offset = count;
return this;
}
build() {
return { ...this.query };
}
// Simulated query execution
execute(database) {
const query = this.build();
console.log("Executing query:", JSON.stringify(query, null, 2));
let results = [...database];
// Filtering
if (query.filters.species) {
results = results.filter(d => d.species === query.filters.species);
}
if (query.filters.diet) {
results = results.filter(d => d.diet === query.filters.diet);
}
if (query.filters.minDanger) {
results = results.filter(d => d.dangerLevel >= query.filters.minDanger);
}
if (query.filters.isActive !== undefined) {
results = results.filter(d => d.isActive === query.filters.isActive);
}
// Sorting
if (query.sort) {
results.sort((a, b) => {
const dir = query.sort.direction === "asc" ? 1 : -1;
if (a[query.sort.field] === b[query.sort.field]) return 0; // equal values
return a[query.sort.field] > b[query.sort.field] ? dir : -dir;
});
}
// Pagination
results = results.slice(query.offset, query.offset + query.limit);
return results;
}
}The where... methods only record filters in the query object - nothing is filtered yet. Only execute() runs a copy of the database through filter(), sorts it and trims it with slice(), while the original array stays untouched. The compare function returns 0 for equal values, because sort() requires a consistent comparison.
Now a sample database and a query made of five readable steps:
// Sample database
const dinoDatabase = [
{ name: "Rexy", species: "Tyrannosaurus", diet: "carnivore", dangerLevel: 10, isActive: true },
{ name: "Blue", species: "Velociraptor", diet: "carnivore", dangerLevel: 8, isActive: true },
{ name: "Spike", species: "Triceratops", diet: "herbivore", dangerLevel: 4, isActive: true },
{ name: "Echo", species: "Velociraptor", diet: "carnivore", dangerLevel: 7, isActive: false },
{ name: "Trike", species: "Triceratops", diet: "herbivore", dangerLevel: 3, isActive: true }
];
// Building a query with Fluent API
const dangerousCarnivores = new DinoQueryBuilder()
.whereDiet("carnivore")
.whereDangerAbove(7)
.whereActive()
.sortBy("dangerLevel", "desc")
.limitTo(5)
.execute(dinoDatabase);
console.log("Dangerous carnivores:", dangerousCarnivores);
// [{ name: "Rexy", ... }, { name: "Blue", ... }]Out of five dinosaurs, Rexy and Blue remain: the herbivores fail the diet filter, and Echo fails the activity filter. You will find the same style in many libraries that build database queries.
Builder with Validation and Default Values
A builder can also enforce the park's safety rules. The constructor sets sensible defaults, and the methods check the data and record errors instead of stopping the build halfway:
class EnclosureBuilder {
constructor(name) {
this.enclosure = {
name,
type: "standard",
fenceVoltage: 10000,
size: 1000,
features: [],
maxCapacity: 5,
currentDinosaurs: []
};
this.errors = [];
}
setType(type) {
const validTypes = ["standard", "aquatic", "aviary", "high-security"];
if (!validTypes.includes(type)) {
this.errors.push(`Invalid enclosure type: ${type}`);
}
this.enclosure.type = type;
return this;
}
setFenceVoltage(voltage) {
if (voltage < 5000) {
this.errors.push("Fence voltage must be >= 5000V");
}
this.enclosure.fenceVoltage = voltage;
return this;
}
setSize(squareMeters) {
if (squareMeters < 100) {
this.errors.push("Minimum area is 100 mยฒ");
}
this.enclosure.size = squareMeters;
return this;
}
setMaxCapacity(capacity) {
this.enclosure.maxCapacity = capacity;
return this;
}
addFeature(feature) {
this.enclosure.features.push(feature);
return this;
}
addDinosaur(dinosaur) {
if (this.enclosure.currentDinosaurs.length >= this.enclosure.maxCapacity) {
this.errors.push(`Enclosure full! Max: ${this.enclosure.maxCapacity}`);
}
this.enclosure.currentDinosaurs.push(dinosaur);
return this;
}
build() {
if (this.errors.length > 0) {
throw new Error(
`Enclosure build errors:\n${this.errors.join("\n")}`
);
}
return Object.freeze({ ...this.enclosure }); // Frozen object
}
}Errors pile up in the errors array, so build() reports all the problems at once, not just the first one. Object.freeze() freezes the finished enclosure, but only at the top level - you can still add something to the features array.
Building an enclosure for the raptors passes validation, because the voltage, area and number of residents are within limits:
// Building an enclosure
const raptorPaddock = new EnclosureBuilder("Raptor Paddock")
.setType("high-security")
.setFenceVoltage(25000)
.setSize(5000)
.setMaxCapacity(4)
.addFeature("electrified-fence")
.addFeature("motion-sensors")
.addFeature("reinforced-gates")
.addDinosaur("Blue")
.addDinosaur("Charlie")
.addDinosaur("Delta")
.build();
console.log(raptorPaddock);
// { name: "Raptor Paddock", type: "high-security", fenceVoltage: 25000,
// size: 5000, features: [...], maxCapacity: 4, currentDinosaurs: [...] }If someone set the voltage to 3000 V, build() would throw an exception with the list of errors and no enclosure would be created. Fields you don't set keep the default values from the constructor.
Functional Builder (Without Classes)
Builder doesn't require classes - we can use simple functions. The report's state lives in a closure, and the methods return the builder object instead of this:
function createDinoReport(name) {
const report = { name, sections: [] };
const builder = {
addVitals(heartRate, temperature) {
report.sections.push({ type: "vitals", heartRate, temperature });
return builder;
},
addBehavior(description, threatLevel) {
report.sections.push({ type: "behavior", description, threatLevel });
return builder;
},
addNote(text) {
report.sections.push({
type: "note",
text,
timestamp: new Date().toISOString()
});
return builder;
},
build() {
return {
...report,
generatedAt: new Date().toISOString(),
totalSections: report.sections.length
};
}
};
return builder;
}The report variable cannot be reached from outside, so you can change it only through the builder's methods. Returning builder instead of this means a method still works even when someone takes it out of the object and calls it on its own.
We assemble the veterinary report from five entries and one build() call:
// Building a report
const report = createDinoReport("Rexy")
.addVitals(65, 38.2)
.addBehavior("Calm, eating regularly", "low")
.addNote("New hunting pattern observed")
.addVitals(120, 39.1)
.addBehavior("Agitated after the storm", "medium")
.build();
console.log(JSON.stringify(report, null, 2));The build() method adds a generation timestamp and the number of sections, 5 here, and JSON.stringify(report, null, 2) prints the result with indentation.
Summary
Dr. Wu summarizes: "The Builder pattern is like the protocol for creating a dinosaur - step by step, with validation at each stage:"
- Builder - constructs complex objects step by step instead of one massive constructor
- Fluent API / Method chaining - each method returns
this, enabling chained calls - Validation -
build()checks correctness before creating the object - Readability - code is self-documenting, each parameter has a named method
The Builder pattern is especially useful when:
- An object has many optional parameters
- You want to validate data before creating the object
- You're building queries, configurations, or complex data structures
My advice: reach for the Builder pattern when there are many optional fields. With two or three, a constructor that takes a single options object, such as new Dinosaur({ name, diet }), is enough, because the field names document the code themselves. In the next lesson you will create custom error classes, so that build() can report a problem more precisely than a plain Error. In the lab below you will build a ReportBuilder based on method chaining.
Remember: Builder is the hatchery protocol - a dinosaur is created step by step and comes out into the world only after passing inspection in build().
Code for this lesson: index.js
// The Builder pattern in JavaScript
// Jurassic Park - Creating complex objects
console.log("=== BUILDER PATTERN ===");
// A builder for dinosaurs
class DinosaurBuilder {
constructor(name, species) {
this.dinosaur = { name, species, abilities: [] };
}
setDiet(diet) {
this.dinosaur.diet = diet;
return this; // Returns this - enables chaining
}
setAge(age) {
this.dinosaur.age = age;
return this;
}
setWeight(weight) {
this.dinosaur.weight = weight;
return this;
}
setHabitat(habitat) {
this.dinosaur.habitat = habitat;
return this;
}
setDangerLevel(level) {
this.dinosaur.dangerLevel = level;
return this;
}
addAbility(ability) {
this.dinosaur.abilities.push(ability);
return this;
}
build() {
if (!this.dinosaur.diet) {
throw new Error("A diet is required!");
}
return { ...this.dinosaur };
}
}
// Creating a dinosaur with method chaining
const rexy = new DinosaurBuilder("Rexy", "Tyrannosaurus")
.setDiet("carnivore")
.setAge(8)
.setWeight(12000)
.setHabitat("Sector A")
.setDangerLevel(10)
.addAbility("hunt")
.addAbility("roar")
.build();
console.log("Rexy:", rexy);
const blue = new DinosaurBuilder("Blue", "Velociraptor")
.setDiet("carnivore")
.setAge(4)
.setWeight(80)
.setDangerLevel(8)
.addAbility("hunt")
.addAbility("communicate")
.addAbility("coordinate-pack")
.build();
console.log("Blue:", blue);
// === FLUENT QUERY BUILDER ===
console.log("\n=== QUERY BUILDER ===");
class DinoQueryBuilder {
constructor() {
this.query = { filters: {}, sort: null, limit: 100 };
}
whereDiet(diet) {
this.query.filters.diet = diet;
return this;
}
whereDangerAbove(level) {
this.query.filters.minDanger = level;
return this;
}
sortBy(field, direction = "asc") {
this.query.sort = { field, direction };
return this;
}
limitTo(count) {
this.query.limit = count;
return this;
}
execute(database) {
let results = [...database];
const f = this.query.filters;
if (f.diet) results = results.filter(d => d.diet === f.diet);
if (f.minDanger) results = results.filter(d => d.dangerLevel >= f.minDanger);
if (this.query.sort) {
const dir = this.query.sort.direction === "asc" ? 1 : -1;
results.sort((a, b) =>
a[this.query.sort.field] > b[this.query.sort.field] ? dir : -dir
);
}
return results.slice(0, this.query.limit);
}
}
const db = [
{ name: "Rexy", diet: "carnivore", dangerLevel: 10 },
{ name: "Blue", diet: "carnivore", dangerLevel: 8 },
{ name: "Spike", diet: "herbivore", dangerLevel: 4 },
{ name: "Echo", diet: "carnivore", dangerLevel: 7 },
{ name: "Trike", diet: "herbivore", dangerLevel: 3 },
];
const dangerous = new DinoQueryBuilder()
.whereDiet("carnivore")
.whereDangerAbove(7)
.sortBy("dangerLevel", "desc")
.limitTo(5)
.execute(db);
console.log("Dangerous carnivores:", dangerous);
// === BUILDER WITH VALIDATION ===
console.log("\n=== BUILDER WITH VALIDATION ===");
class EnclosureBuilder {
constructor(name) {
this.enclosure = { name, type: "standard", features: [], dinosaurs: [] };
this.errors = [];
}
setType(type) {
const valid = ["standard", "aquatic", "aviary", "high-security"];
if (!valid.includes(type)) this.errors.push("Invalid type: " + type);
this.enclosure.type = type;
return this;
}
addFeature(feature) {
this.enclosure.features.push(feature);
return this;
}
addDinosaur(name) {
this.enclosure.dinosaurs.push(name);
return this;
}
build() {
if (this.errors.length > 0) {
throw new Error("Errors: " + this.errors.join(", "));
}
return Object.freeze({ ...this.enclosure });
}
}
const paddock = new EnclosureBuilder("Raptor Paddock")
.setType("high-security")
.addFeature("electrified-fence")
.addFeature("motion-sensors")
.addDinosaur("Blue")
.addDinosaur("Charlie")
.addDinosaur("Delta")
.build();
console.log("Paddock:", paddock);
// TODO: Create a ReportBuilder with method chaining
// addVitals(), addBehavior(), addNote(), build()
console.log("\n=== Exercise ===");
console.log("Create the ReportBuilder - see the TODO in the code");Docs entries used in this lesson
Spotted a mistake in this lesson?
Hands-on tasks in the game
- Horizontal ordering
Arrange the elements for creating an object with the Builder pattern:
- Click in order
Arrange the elements of a Builder method that enables chaining: