Learnitweb

What is a first-class function?

In JavaScript, a first-class function refers to the ability of functions to be treated like any other value. This means functions in JavaScript can:

  • Be assigned to variables:
    • A function can be stored in a variable just like any other value.
  • Be passed as arguments:
    • Functions can be passed as arguments to other functions.
  • Be returned from other functions:
    • Functions can return other functions.
  • Be stored in data structures:
    • Functions can be stored in arrays, objects, or other data structures.

These properties make functions “first-class citizens” in JavaScript.

Key Characteristics of First-Class Functions

Assigning to Variables

const greet = function(name) {
    return `Hello, ${name}!`;
};
console.log(greet('Alice')); // "Hello, Alice!"

Passing as Arguments

function sayHello() {
    return 'Hello!';
}

function greetUser(greetingFunction) {
    console.log(greetingFunction());
}

greetUser(sayHello); // "Hello!"

Returning Functions

function multiplier(factor) {
    return function(number) {
        return number * factor;
    };
}

const double = multiplier(2);
console.log(double(5)); // 10

Storing in Data Structures

const operations = {
    add: (a, b) => a + b,
    multiply: (a, b) => a * b
};

console.log(operations.add(2, 3)); // 5
console.log(operations.multiply(2, 3)); // 6

Why First-Class Functions are Powerful

Higher-Order Functions:

Functions that take other functions as arguments or return functions are called higher-order functions. Examples: Array.map, Array.filter, Array.reduce.

const numbers = [1, 2, 3, 4];
const squares = numbers.map((n) => n * n);
console.log(squares); // [1, 4, 9, 16]

Functional Programming:

First-class functions enable a functional programming style where functions are used as building blocks for computation.