## DEV Community 👩‍💻👨‍💻 Umashankar S

Posted on • Updated on

# Higher Order Functions in JS

Write a snippet of functions to calculate area, circumference and diameter of the circle.

• without higher order function (repetitive code):
``````const radius = [2,3,4,5,6,7];
let output = [];

output = [];
}
return output;
}
output = [];
}
return output;
}
output = [];
}
return output;
}
``````

If we saw the above code, area, circumference and diameter functions are almost same except that maths formula. so we make that as a generalized function using higher order functions.

• with higher order function (function that takes another functions as an argument or returns a function)
``````const radius = [2,3,4,5,6,7];
let output = [];

const area = function(value) {
return Math.PI*value*value;
}

const circumference = function(value) {
return 2*Math.PI*value;
}

const diameter = function(value) {
return 2*value;
}

const calculate = function(radius, logic) {
output = [];
}
return output;
}

``````

Here we are creating one generalized function , that will accept another function as a input parameter (Higher Order function).

• with ES6 feature Map. In the Above section , we created higher order function to perform the operation, and we can achieve the same thing by using the exisiting javascript function called "Map".
``````const radius = [2,3,4,5,6,7];

const area = function(value) {
return Math.PI*value*value;
}

const circumference = function(value) {
return 2*Math.PI*value;
}

const diameter = function(value) {
return 2*value;
}

``````

• Cloning of Map function using higher order function. (Map Polyfill). Like Map, we can also create our own prototypes and operations using higher order functions like below.
``````const radius = [2,3,4,5,6,7];
let output = [];

const area = function(value) {
return Math.PI*value*value;
}

const circumference = function(value) {
return 2*Math.PI*value;
}

const diameter = function(value) {
return 2*value;
}

Array.prototype.calculate = function(logic) {
output = [];
for(i=0;i<this.length;i++){
output.push(logic(this[i]));
}
return output;
}

`````` Luke Shiru

A few things:

• You should avoid mutations of the native objects prototypes, such as `Array`. So to any junior reading this: Avoid code like the last example.
• Your examples are mutating `output`, ideally that `output` variable should only live inside `calculate`.
• Your first example of HOC could use some modernization, and it actually doesn't need `calculate`, you can just use the native `Array.prototype.map`:
``````const radiuses = [2, 3, 4, 5, 6, 7];

``````

Cheers! Umashankar S • Edited on

Yes, That is correct. we should not touch the Array prototypes (we should not mutate that).
But Just I'm explaining that how we can create our own functions like maps using the Higher order functions. Yes, we can use the modern arrow functions , instead of normal functions.  