What is a first-class function in JavaScript?

What is a first-class function in JavaScript?
Reading Time: < 1 minute

In JavaScript, a first-class function is a function that can be treated just like any other variable in the language, such as a number, string, or object. This means that you can pass a function as an argument to another function, return a function from a function, store a function in a variable, and use a function as a property of an object, among other things.

Here’s an example to demonstrate the concept of a first-class function in JavaScript:

// Define a function
function square(x) {
  return x * x;
}

// Assign the function to a variable
const squareFunction = square;

// Pass the function as an argument to another function
function callFunction(func, x) {
  return func(x);
}

// Use the function stored in a variable
console.log(squareFunction(5)); // 25

// Use the function passed as an argument
console.log(callFunction(square, 5)); // 25

In this example, the square function is a first-class function because it can be stored in a variable, passed as an argument to another function, and used like any other value in JavaScript.

,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Join 22 other subscribers

Leave a Reply