Skip to main content

Command Palette

Search for a command to run...

JavaScript Higher Order function (HOF)

Published
2 min read

What is Higher Order Function ?

A Higher Order Function is a function that does at least one of the following

  • Takes another function as an argument

  • Return another function as it’s result

Importance of Higher Order Function ?

  • Write clean and readable code

  • Reuse behavior

  • Separate logic from iteration

Example 1 ( Function as an argument )

function fn1() {
    console.log('Hello world !!');
}

function fn2(action) {
    action();
    action();
}

fn2(fn1);

/*
    output

    Hello world !!
    Hello world !!
*/

in this example fn2 is a higher order function because it takes another function as an argument

Working of EX-1

Example 2 ( Function returning another function )

function multiplier(factor) {
  return function (number) {
    return number * factor;
  };
}

const double = multiplier(2);
double(5); 

/*
    output
    10
*/

working of Ex-2

Some Higher Order Functions are -

  • map()

  • filter()

  • reduce()

  • forEach()

  • sort()

Custom polyfills for Array higher-order methods

map()

// callbackfn: (value: number, index: number, array: number[])
function myMap(array, callback) {
    const result = [];

    for(let i=0; i < array.length; i++) {
        result.push(callback(array[i], i, array));
    }

    return result;
}

filter()

// predicate: (value: number, index: number, array: number[])

function myFilter(array, callback) {
    const result = [];

    for(let i=0; i < array.length; i++) {
        if(callback(array[i], i, array)) {
            result.push(array[i]);
        }
    }

    return result;
}

reduce()

// callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: number[]) 

function myReducer(array, callback, initialValue){
    let accumulator = initialValue;

    for(let i=0; i < array.length; i++) {
        accumulator = callback( accumulator, array[i], i, array)
    }

    return accumulator;
}

forEach()

// callbackfn: (value: number, index: number, array: number[])
function myForEach(array, callback) {

    for(let i=0; i < array.length; i++) {
        callback(array[i], i, array);
    }
}

sort()

// sort(compareFn?: ((a: number, b: number)
function mySort(array, compareFn) {
    for(let i=0; i < array.length; i++) {
        for(let j=i+1; j < array.length; j++) {
            if(compareFn(array[i], array[j]) > 0) {  
                [array[i], array[j]] = [array[j], array[i]];
            }
        }
    }
    return array;
}

Higher-order function are one of the most powerful feature and a key part or writing clean, maintainable code.