Sign in
Log inSign up

Closures, First-class Functions, and Higher-Order Function.

Samuel Christopher's photo
Samuel Christopher
·Mar 16, 2022·

6 min read

A simple article that explores function closures, first-class function, and higher-order function.

Target Audience

This article is for anyone in programming. Anyone that wants to understand function closures, functions as first-class; and higher-order functions;

Learning Objectives

After reading this article, you will know how to do the following:

  • Understand functions as first class.
  • Parsed in function as an argument.
  • Return a function within another function.
  • Assign a function to a variable.
  • Identify a higher-order function.
  • Understand function closures.

It takes years of focused practice to become a great engineer. This article will improve your knowledge of functions in Javascript. But, won't turn you into an expert in Javascript.

First Class Function

A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions. A function can be returned by another function. And a function can be assigned as a value to a variable.

Parsed as an argument

function print(value) {
  console.log(value);
}

function greet(name, callFun) {
  callFun("Hello " + name);
}

greet("Sammy", print); // Hello Sammy

The above example passes the print() function as the second argument to the greet() function. But, named callFun in the greet() function. This explains passing a function as an argument.

Note: The second parameter in the greet() function named callFun is a callback function in Javascript. A callback is a function passed as an argument to another function.

Return by another function

function house() {
  return function () {
    console.log("Hello");
  };
}

house()(); // Hello

The above example returns a function within the house() function. The explains the part says a function can be returned by another function. That's because Javascript treats functions like value.

Notice the house() function returns a function with no name. That is an anonymous function in Javascript.* An anonymous function is a function with no name.

Note: A function that returns a function is called a Higher-Order Function.

Assigned to a variable

var printHello = function () {
  console.log("Hello");
};

The above example assigns a function to a variable named printHello. Remember, the function assigned to the variable printHello is an anonymous function. You will use the variable printHello to invoke the function. A variable name followed by parenthesis, like this.

printHello();

Higher-Order Function

A function that takes one or more functions as arguments, or returns a function as its result. This is mostly used in functional programming, from which most functional programming languages are derived.

Takes a function as an argument

Function delay2sec(callback) {
    setTimeout(() => {
        callback('Something');
    }, 2000);
}
add(console.log); // Something

The above example passes console.log object method as an argument that triggers in the delay2sec() function after the space of 2 seconds. This is useful when making an API request.

Because after the code is done executing, the API takes a longer time to get the data. This is the reason why using a callback function serves best.

This approach is known as an asynchronous call. It's mostly used in Nodejs because it's single-threaded, and upon this approach is the idea of promises, async, and awaits are being generated from.

Returns a function as a result

function outSide() {
    return function () {
        console.log(‘inside function’);
    }
}

Another Example.

function outSide() {
  let num = 5;
  return function () {
    return num;
  };
}

Notice the outSide() function returns a function. Any variable in the outSide() function becomes global to the returned function. In this case, the num variable in the outSide() function is global to the returned function. Now, this is known as a function closure.

Closures

A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

Variables in Javascript can either be global or local depending on where it’s been created. A local variable is a variable that is given local scope. A global variable, is a variable with global scope, meaning that it is accessible in all parts of the code.

Example of Local Variables

function starting() {
  let num = 0;
  // local variable
}

The variable num is a local variable because it only exists within the scope of starting() function. And can not be visible outside the starting() function.

Note: A local variable can exist inside a function, class, object, etc. only within its local environment (scope).

Example of Global Variable

let num = 0;

function first() {
  console.log(num);
}

function second() {
  console.log(num);
}

Based on the above example, the variable num is a global variable. Because it's visible to all parts of the code. For example, it's accessible to the first() and second() functions.

Back to closures. A returned function has access to all variables in its parent function.

function host() {
  let num = 0;
  // local variable

  return function () {
    console.log(num);
  };
}

var result = host();

result(); // 0

The above example invokes the host() function. And returns a value (another function). Stores the returned value (another function) to the variable result. And finally, invokes the result() as a function. Because a function is stored to the variable named result.

Notice the final value is 0. This is the work of closure. A child function has access to the variables in the parent function. Like the above example, where the host() declares a num variable within its scope before returning a child function. This returned child function has access to the variable num. Because the variable num and the child function share the same (parent) scope.

Another example of function closures.

function host() {
  let num = 0;
  // local variable

  return function () {
    num++;
  };
}

let firstCall = host();

firstCall(); // 1
firstCall(); // 2
firstCall(); // 3

The parent function (host()) declares a variable named num and sets its value it 0. And returns a child function with its local scope. This gives the child function access to the variable num.

Notice after invoking the host() function returns a value (child function) with its local scope. This function is then assigned together with its local scope to the new variable named firstCall. Whenever firstCall function gets invoked it access the parent scope which was already declared after calling the host() function.

For this reason, upon every firstCall() function call the variable num gets incremented.

Conclusion

This is a straightforward article that explores function closure, functions as first-class value, and higher-order function. As stated above, you've explored function as a first-class value. This is where a function is treated as a value in Javascript. And a higher-order function, where a function that takes one or more functions as arguments, or returns a function as its result. lastly, function closures, are a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). By now, your understanding of function in Javascript must have improved. And the different ways you can implement it.

Thanks.