What is a first-class function in JavaScript

A first-class function in JavaScript means that functions are treated like any other value. This means functions can:

  1. Be assigned to variables.
  2. Be passed as arguments to other functions.
  3. Be returned from other functions.
  4. Be stored in data structures like arrays and objects.

Example: Assigning a function to a variable

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

Example: Passing a function as an argument

function executeFunction(fn, value) {
    return fn(value);
}

const square = (num) => num * num;

console.log(executeFunction(square, 5)); // Output: 25

Example: Returning a function from another function

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

const double = multiplyBy(2);
console.log(double(10)); // Output: 20

Since functions in JavaScript can be assigned, passed around, and returned just like any other value, they are considered first-class citizens in JavaScript. 🚀

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *