JavaScript
  • JavaScript Introduction
  • JS Engine
  • V8 Engine
  • First-class function
  • Optimized Code
  • Call Stack & Memory heap
  • Single Thread
  • JavaScript RunTime
  • Nodejs
  • Context and Environment
  • Hoisting
  • Functions
  • Arguments
  • Variables
  • Scope
  • IIFE
  • this
  • call(), apply() and bind()
  • currying
  • Types
  • Type Coercion
  • Functions as Object
  • HOF (Higher Order Function)
  • Two pillars of Javascript
  • Closures
  • Prototypal Inheritance
  • OOP and FP
  • OOP
    • 4 principles of OOP
  • FP
    • Pure function
    • Imperative vs Declarative
    • Immutability
    • HOF and Closures
    • Currying
    • Partial Application
    • Compose and Pipe
  • Composition vs Inheritance
  • OOP vs FP
  • JS working
  • Promises
  • Async Await
  • ES5 - ECMAScript 2009
  • ES6 - ECMAScript 2015
  • ES7 - ECMAScript 2016
  • ES8 - ECMAScript 2017
  • ES9 - ECMAScript 2018
  • ES10 - ECMAScript 2019
  • ES11 - ECMAScript 2020
  • ES12 - ECMAScript 2021
  • JOB Queue
  • Promises Execution
Powered by GitBook
On this page

Was this helpful?

HOF (Higher Order Function)

A function that take a function as argument or returns a function is know as Higher Order Function.

It’s higher-order because instead of strings, numbers, or booleans, it goes higher to operate on functions.

Returning Function:

Ex 1:

const add = function(x) {
    return function(y) {
       return x+y;
    }
}

const sum = add(2)(3); // 5

add requires two parameters, but not all at once. It’s a function asking for just x, that returns a function asking for just y. Again, this is only possible because JavaScript allows functions to be a return value — just like strings, numbers, booleans, etc. You can still supply x and y immediately, if you wish, with a double invocation

Function as Argument:

Ex 2:

function MultiplyByTwo(a) {
    return 2 * a;
}

const multiply = function(num, fn) { // accepts number and function as argumnet
    return fn(num);
}

const result = multiply(3, MultiplyByTwo); // 6

MultiplyByTwo function multiplies the give number with 2. multiply function takes two argument first one as number and second is function. I have passed the number 3 and MultiplyByTwo function as an argument to multiply function. multiply function will returns the 2 multiplied by 3 value as 6

PreviousFunctions as ObjectNextTwo pillars of Javascript

Last updated 5 years ago

Was this helpful?