Published on

Higher-Order Functions, Callback Function, and Closures in JavaScript

featured Image

We'll look at the HOF (Higher-order function), Callbacks, and the wacky JavaScript Closures in this post, which have all made us pull our hair out at some point throughout our learning path.

1. Higher-Order Functions(HOF)


Functions can be assigned to variables in Javascript in the same manner that strings, numbers, booleans, and arrays can. They can be supplied as arguments to other functions or returned from them.

A function that accepts functions as parameters and/or returns a function is referred to as a "higher-order function."

For example

const isEven = (x) => x > 0 && x % 2 === 0

const logger = (Fn, Num) => {
  const isEven = Fn(Num)

logger(isEven, 6)

Because it accepts the isEven function as an input, "logger" is the Higher-Order Function in the preceding excerpt.

Some JavaScript methods like map, filter, reduce etc are higher-order functions.

2. Callback Function


A callback is a function that is supplied as an input to another function and then runs later. isEven is the callback function in the last code snippet.

A callback is a function that is sent to another function as an argument.

After another function has been completed, a callback function can be called.

For example

const logger = (output) => console.log(output)

const add = (x, y, callback) => {
  const z = x + y

add(51, 96, logger)

In this code snippet, logger is a callback function that is passed to add function as argument and called after adding two number to display result.

Async JavaScript can be handled via callback functions.

3. Closures


Variables in JavaScript can be in the local or global scope. Closures can be used to make global variables local (private).

A closure is a function that continues to have access to the outer variables after the outer function has been returned.

let countryCode = '+1'

function getPhoneNumber() {
  let phone = '2354687262'
  function encryptedPhone() {
    // A closure function
    let encryptedNumber = phone * 5
    return countryCode + encryptedNumber

  return encryptedPhone
getPhoneNumber()() // +111773436310

The closure function encryptedPhone in the following code snippet has access to the outer variables (countryCode and phone).

Because of Lexical Scoping, closures are possible in JS. If a variable is not discovered in the local scope, it is searched in the outer scope, and so on until it reaches the global scope.


Note: Except for functions created using the "new Function" syntax, every function in JavaScript is a closure.

Thanks for reading this article.

If you have any queries, feel free to contact me here