This page looks best with JavaScript enabled

Create Chainable Interfaces in Javascript

 ·   ·  ☕ 1 min read

Chainable interfaces make your code readable and, arguably, your life more enjoyable.

Chainable interfaces are those series of methods that you see chained to an object. You can use them for objects where “relevant”.

Commonly used functions

It is common to see methods chained to one another. The chaining works from left to right, with results from the left-side of the function passed to the right in sequence.

1
2
3
4
5
6
const message = "hello world";
const newMsg = message
  .replace("h", "y")
  .toUpperCase()
  .substr(0, 6);
console.log("message: ", newMsg); // YELLO

Custom Objects

One of the ways of demonstrating chainable interfaces for our own objects is by defining a function, and defining props and prototypes for the function.

We will define a function and the prototypes of that function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const Fruit = function(color, shape) {
  this.color = color;
  this.shape = shape;
};

Fruit.prototype.setColor = function(color) {
  this.color = color;
  return this;
};
Fruit.prototype.setShape = function(shape) {
  this.shape = shape;
  return this;
};

Now, I can use chained methods to set values.

1
2
3
const apple = new Fruit().setColor("red").setShape("round");
console.log("apple: ", apple);
// Fruit { color: 'red', shape: 'round' }
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things