JavaScript Programming Paradigms

1 minute read

JavaScirpt is one of the most important programming languages of all time, not simply because of its popularity, but because it popularized two paradigms which are extremely important for the evolution of programming.

Can you name two programming paradigms important for JavaScript app developers?

JavaScript is multi-paradigm language, supporting imperative/procedural programming along with OOP (Object-Oriented Programming) and functional programming. JavaScript supports OOP with prototypal inheritance.

Prototyppal inheritance (prototypes, OLOO)

Objects without classes, and prototype delegation, aka OLOO - Objects Linking to Other Objects)

Objects in JavaScript have an internal property [[Ptototype]], which is a reference to another object. Prototypal Inheritance: instancses inherit directly from other objects. Instances are typically instantiated via factory functions or Object.create(). Instances may be composed from many different objects, allowing for easy selective inheritance. In prototypal inheritance, instances inherit from other instances. Using delegate prototypes (settiing the prototype of one instance to refer to an examplar object), it’s literally Objects Linking to Other Objects or OLOO, as Kyle Simpson calls it. Using concatenative inheritance, you just copy properties from an examplar object to a new instances.

A prototype is just a working sample

There are two (+ 1) kinds of prototypes:

  • Delegate Prototype - when you don’t find what you are looking in the object you look it up in the object prototype

const proto = {
  hello() {
    return 'Hello, my name is ' + this.name;
  }
};

const george = Object.create(proto);
george.name = 'George'
console.log(george.hello()); // Hello, my name is George

You can attach delegate prototype with Object.create()


let animal = {
  animalType: 'animal',

  describe() {
    return `An ${this.animalType}, with ${this.furColor} fur,
    ${this.legs} legs, and a ${this.tail} tail.`;
  }
};

let mouse = Object.asssign(Object.crete(animal), {
  animalType: 'mouse',
  furColor: 'brown',
  legs: '4',
  tail: 'long, skinnny'
});

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

  • Cloning / Concatenation - copy all properties from other objects (mixin, great for default state)

    Mixin style


  const proto = {
    hello() {
      return `Hello, my name is ${this.name}!`
    }
  }

  const george = _.extend({}, proto, { name: 'George' });

  • Functional inheritance
    • Great for encapsulation / privacy
    • Functional mixins