HomeJAVASCRIPTWhat are first-class functions?

What are first-class functions?

In programming, first-class functions (also called first-class citizens) mean that functions are treated like any other value. In languages that support this, you can:

  1. Assign functions to variables
const greet = function(name) {
  return `Hello, ${name}!`;
};
  1. Pass functions as arguments to other functions
function sayHello(fn) {
  console.log(fn("Himanshu"));
}

sayHello(greet); // Hello, Himanshu!
  1. Return functions from other functions
function multiplier(factor) {
  return function(number) {
    return number * factor;
  };
}

const double = multiplier(2);
console.log(double(5)); // 10
  1. Store functions in data structures (arrays, objects, etc.)
const operations = [x => x + 1, x => x * 2];
console.log(operations ); // 10

Key idea: Functions are just values — you can store, pass, and return them like numbers or strings.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

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