Higher order function JavaScript
A function takes another function as an argument and return a function as a value. it is known as Higher Order Function.
JavaScript functions are first class citizen
function sayHello() { return function(){ return "Hello world"; } } let fn = sayHello(); let message = fn();Higher order function
let number = [1,2,3]; number.map(number =>number*2)map() is a higher order function in JavaScript becouse it take a function as an argument. another example of higher order function is setTimeOut()
setTimeOut(()=> console.log("Hello"), 1000);Ex. (normal method )
const radius = [3, 1, 2, 4];// calculate the area of this four circlesconst calculateArea = function(radius){const temp = []for(let i = 0; i<radius.length ; i++ ){temp.push(2*Math.PI*radius[i]*radius[i])}return temp}console.log(calculateArea(radius))// calculate cercumference of this four circleconst carcumference = function(radius){const temp = []for(let i = 0; i<radius.length; i++){temp.push(2*Math.PI*radius[i])}return temp}console.log(carcumference(radius))
[ 56.548667764616276, 6.283185307179586, 25.132741228718345, 100.53096491487338 ] [ 18.84955592153876, 6.283185307179586, 12.566370614359172, 25.132741228718345 ]Using higher order function ( Don't Repeat Yourself)
const radius = [3, 1, 2, 4];const area = function (radius) {return Math.PI * radius * radius}const circumference = function (radius){return 2*Math.PI *radius}const calculate = function (radius, logic) {const temp = []for (let i = 0; i < radius.length; i++) {temp.push(logic(radius[i]));}return temp}console.log(calculate(radius, area))console.log(calculate(radius, circumference))
[ 28.274333882308138, 3.141592653589793, 12.566370614359172, 50.26548245743669 ] [ 18.84955592153876, 6.283185307179586, 12.566370614359172, 25.132741228718345 ]
Post a Comment