First Class Functions

Examples of functions as first class objects

In JavaScript, functions can be passed in as arguments to functions, returned as values from functions, assigned to variables, and stored in data structures.

This makes functions first-class objects.

Here’s a summary of what we know about functions in JavaScript:

  1. A function is an instance of the Object type;
  2. A function behaves like any other object;
  3. We can store functions in a variable;
  4. We can pass a function as an argument to another function;
  5. We can return a function from a function;

Passing functions as arguments

Let’s look at the following example of passing a function as an argument:

We call the function arrayCalc, and pass in the years array and the calculateAge function as the arguments. As a result, arrayCalc calculates the ages for each element in the years array and returns the ages in an array called arrRes.

Functions returning Functions

Let’s now take a look at an example where functions are returned from other functions:

Here we have a function, interviewQuestion, that returns a different function depending on the type of job that was given as the input. For example, if the job input was designer, the output is a function that logs the string “{name}, can you please explain what UX design is?”

Since the result of the interviewQuestion function is an anonymous function, we have to store the result in a variable to be able to call it later. As you can see, we store the function returned by passing in designer in the designerQuestion variable. Now, to call the designerQuestion function, we simply call the variable and pass in the name of the person, such as designerQuestion(‘Jane’).

In this example, we created one generic function, the interviewQuestion, and then a set of more specific functions (var teacherQuestion and var designerQuestion).

Hopefully, this shows you how useful this technique can be. Once understood, it can be a powerful way of using functions.

Show your support

Clapping shows how much you appreciated Lena Sabaeva’s story.