First Class Function in Javascript

First Class Function in Javascript

Understanding functions and their implementation is really important to write effective, robust functional programming using Javascript. This comes with great design patterns and ideas which makes the code more flexible, scalable and less prone to bugs. We will be discussing how functions are treated in Javascript and the power it gives to the language.

First-class Function

When the functions are treated like any other variables in a programming language, then that language is said to have first-class functions. For example -

  • the function can be passed as an argument to other functions

  • the function can be returned by another function

  • the function can be assigned as a value to a variable

Let's understand this by some code examples -

Assigning a function to a variable

const greet = () => {
  console.log("Hello");
};
greet(); // Invoke it using the variable name
//Output -  Hello

Isn't it amazing! We have assigned an anonymous function to a variable greet. Then we used that variable greet to invoke the function by giving () .

Note - Even if you assign a named function to a variable, still you can invoke the function with the variable name. Named functions can be useful for debugging the code.

Passing a function as an argument

function introduce() {
  return "Hello, My name is ";
}
function greeting(message, name) {
  console.log(message() + name);
}
// Pass `introduce` as an argument to `greeting` function
greeting(introduce, "John!");
// Hello, My name is John!

Wow! it's giving more power to use functions so flexibly.

Here, we have implemented introduce() function where we return the common string as Hello, My name is to greet any name. This introduce() function is passed as a reference to the greeting() function with the name to concatenate both strings to create a full greeting message to log on to the console. This is how we treat a function as a value.

Note: The function that we pass as an argument is called a Callback Function. In the above example,introduce() is a callback function.

Returning a function from another function

function appCounter() {
  let count = 0;
  return () => {
    console.log(++count);
  };
}

let counter = appCounter();
counter(); // Output = 1;
counter(); // Output = 2;

This is a simple counter-example. appCounter function returns an anonymous function which is assigned to a counter variable. It logs the incremented value of count variable whenever counter() is invoked.

Note: A function that returns a function or takes other functions as arguments is called a higher-order function.

Did you find this article valuable?

Support Code Craft - Fun With Javascript by becoming a sponsor. Any amount is appreciated!