Table of Contents

JavaScript First-Class Functions are an important feature of JavaScript that allows functions to be treated like any other value. This means functions can be assigned to variables, passed as arguments to other functions, returned from functions, and stored in objects or arrays.

This feature makes JavaScript flexible and supports powerful programming techniques such as callback functions, higher-order functions, and functional programming.

What Are First-Class Functions in JavaScript?

A programming language supports first-class functions when functions can be used as values just like strings, numbers, and objects.

In JavaScript, a function is an object that can be assigned, passed, returned, and stored.

For example:

function greet() {
    console.log("Hello, JavaScript!");
}

console.log(typeof greet);

Output:

function

The typeof operator returns "function", showing that a function is a value that can be referenced and used in JavaScript.

Assigning Functions to Variables

You can assign a function to a variable and call it using that variable.

const greet = function() {
    console.log("Hello, World!");
};

greet();

Output:

Hello, World!

Here, the function expression is assigned to the greet variable. You can invoke the function using greet().

You can also assign an existing function to another variable:

function sayHello() {
    console.log("Hello!");
}

const welcome = sayHello;

welcome();

Output:

Hello!

Notice that sayHello is assigned without parentheses. This assigns the function itself rather than executing it.

Passing Functions as Arguments

JavaScript allows you to pass a function as an argument to another function. This is commonly used with callback functions.

function greet(name) {
    console.log("Hello, " + name);
}

function processUser(callback) {
    const username = "John";
    callback(username);
}

processUser(greet);

Output:

Hello, John

In this example:

  • greet() is the callback function.
  • processUser() accepts a function as an argument.
  • processUser(greet) passes the greet function without executing it.
  • Inside processUser(), callback(username) invokes the passed function.

Returning Functions from Other Functions

A JavaScript function can return another function. This is another important feature of first-class functions.

function createGreeting() {
    return function() {
        console.log("Welcome to JavaScript!");
    };
}

const greeting = createGreeting();

greeting();

Output:

Welcome to JavaScript!

The createGreeting() function returns an anonymous function. The returned function is stored in the greeting variable and executed later.

Storing Functions in Objects

Functions can also be stored as object properties. When a function is stored in an object, it is commonly called a method.

const user = {
    name: "John",
    greet: function() {
        console.log("Hello, " + this.name);
    }
};

user.greet();

Output:

Hello, John

The greet function is stored as a property of the user object and can be called using user.greet().

Storing Functions in Arrays

JavaScript arrays can contain functions just like other values.

const operations = [
    function(a, b) {
        return a + b;
    },
    function(a, b) {
        return a - b;
    },
    function(a, b) {
        return a * b;
    }
];

console.log(operations[0](10, 5));
console.log(operations[1](10, 5));
console.log(operations[2](10, 5));

Output:

15
5
50

Each array element contains a function. You can access and execute a function using its array index.

JavaScript First-Class Functions and Callback Functions

A callback function is a function passed as an argument to another function. JavaScript’s first-class function behavior makes callbacks possible.

function calculate(a, b, callback) {
    return callback(a, b);
}

function add(x, y) {
    return x + y;
}

const result = calculate(10, 20, add);

console.log(result);

Output:

30

The add function is passed to calculate() as an argument. The calculate() function then executes it through the callback parameter.

JavaScript First-Class Functions and Higher-Order Functions

A higher-order function is a function that accepts another function as an argument, returns a function, or does both.

For example, the JavaScript map() method accepts a callback function and creates a new array.

const numbers = [1, 2, 3, 4];

const doubled = numbers.map(function(number) {
    return number * 2;
});

console.log(doubled);

Output:

[2, 4, 6, 8]

The map() method is a higher-order function because it accepts a function as an argument.

JavaScript First-Class Functions with Arrow Functions

Arrow functions can also be assigned to variables and passed as arguments.

const multiply = (a, b) => a * b;

function calculate(callback) {
    console.log(callback(5, 4));
}

calculate(multiply);

Output:

20

The multiply arrow function is passed to calculate() as a callback.

Benefits of First-Class Functions in JavaScript

First-class functions provide several advantages:

  1. Code Reusability: Functions can be passed to different parts of a program and reused.
  2. Callback Support: Functions can be executed after another operation completes.
  3. Higher-Order Functions: You can create functions that accept or return other functions.
  4. Functional Programming: Functions can be composed and used as building blocks for functional programming.
  5. Flexible Code: Functions can be stored in variables, objects, and arrays.

First-Class Functions vs Higher-Order Functions

These two concepts are related but have different meanings.

First-Class Functions Higher-Order Functions
Functions can be treated as values. Functions accept or return other functions.
A language feature or capability. A programming concept built using first-class functions.
Allows assigning functions to variables. Allows passing callbacks or returning functions.
JavaScript supports first-class functions. map(), filter(), and reduce() are examples.

JavaScript supports higher-order functions because functions are first-class values.

Categorized in:

Javascript, JS Basic,