What is Monkey Patch

What is Monkey Patch?

In simple terms, Monkey Patch is a way to extend or modify an existing program or code.

Modifying existing code

Let's say we want to change Math.PI from 3.141592653589793 to be 3.2

We can do it in that way:

Math.PI = 3.2;

Now from anywhere in your application, whenever you use the Math.PI it will be 3.2 instead of 3.141592653589793.

Extending code

Another example of monkey patch is to extend an existing code.

For example there is no method in Javascript to get the last element of the array except the Array.pop which will get and remove it from the array, what if we want to get the element without removing it?

We can do something like:

Array.prototype.end = function () {
    return this[this.length - 1];

Now if we want to get the value of the last element in the array we can use it like:

let numbers = [1, 5, 7, 8, 12];

let lastNumber = numbers.end(); 

console.log(lastNumber); // 12

So is it bad or good principle to adapt?

Actually, it depends, based on the current scenario of the running project, but.. we can't assert as if it is bad or good thing.

So you may use it but with caution to not conflict with other third party applications that uses the same existing code.

Programming Concepts#Programming ConceptsJAVASCRIPT#JAVASCRIPT

Comments (0)