Monkey patching

Monkey patching is a mechanism we can use to replace or extend some piece of code at runtime. A lot of times it is used for overriding methods in third-party libraries or for mocking when writing unit tests.

As an example, let's say we want to add logging to the add method of a math library.

import MathLib from 'mathlib';

const mathLib = new MathLib();
const res = mathLib.add(2, 3);

// we can keep original implementation if we want to
// restore original implementation later on
// const originalAdd = mathLib.add;

// Let's override (monkey patch) original add
// method and replace it with our own implementation
// that supports logging
mathLib.add = function(a, b) {
    console.log(`You are adding ${a} and ${b}.`);
    return a + b;

👍 Pros:

👎 Cons:

Practice time