JavaScript Software Composition

1 minute read

Function composition is the process of applying a function to the output of another function. Composing two functions is chaining process in which the output of the inner function becomes the input of the other function.

JavaScript composition function example:

const g = n => n + 1;
const f = n => n * 2;

const doStuff = x => {
  const afterG = g(x);
  const afterF = f(afterG);
  return afterF;

doStuff(20); // 42

and when we write a promise

const g = n => n + 1;
const f = n => n * 2;
const wait = time => new Promise(
  (resolve, reject) => setTimeout(
  .then(() => 20)
  .then(value => console.log(value)); // 42

“Favor object composition over class inheritance” the Gang of Four, “Design Patterns: Elements of Reusable Object Oriented Software” “In computer science, a composite data type or compound data type is any data type which can be constructed in a program using the programming language’s primitive data types and other composite types. […] The act of constructing a composite type is known as composition.” ~ Wikipedia

Composing objects

These are primitives:

const firstName ='Nexus';
const lastName = 'Star';

And this is composite:

const fullName ={

Acording to Gang of Four there are three kinds of object composition:

  • Delegation (used in state, strategy and visitor pattern)
  • Acquaintance (when an object knows about another object by reference, usally passed as a parameter: a uses-a relationship)
  • Aggregation (when child objects form a part of a parent object: a has-a relationship)

“Favor object composition over class inheritance” ~ GOF

You should form composite objects from small component parts, rather than inheriting all properties from an ancestor in a class hierarchy.

Mixin composition - start with ana object and then mix in the features you want.

class Foo {
  constructor () {
    this.options = options;
    this.a = 'a'

class Bar extends Foo {
  constructor (options) {
    this.b = 'b';

const myBar = new Bar(); // {a: 'a'. b:'b'}

Building composites with mixin composition:

const a = {
  a: 'a'

const b = {
  b: 'b'

const c = { ...a, ...b}; // {a: 'a'. b:'b'}