Raja Muhammad Asher
Raja Muhammad Asher

Follow

Raja Muhammad Asher

Follow
What is a first class function in JavaScript?

Photo by Max Chen on Unsplash

What is a first class function in JavaScript?

Raja Muhammad Asher's photo
Raja Muhammad Asher
·Sep 16, 2022·

1 min read

In JavaScript, functions are first-class citizens, along with numbers, strings, and other data types. You can assign functions to variables, pass them as arguments to other functions, and return them from functions.

// Assign a function to a variable
const sayHello = function() {
  console.log("Hello, World!");
}

// Pass the function as an argument to another function
const callFunction = function(fn) {
  fn();
}
callFunction(sayHello); // Outputs: "Hello, World!"

// Return the function from a function
const createGreeting = function() {
  return sayHello;
}
const greeting = createGreeting();
greeting(); // Outputs: "Hello, World!"
 
Share this