What is First Class Function? First Class Function in JavaScript

diwakarkashyap

DIWAKARKASHYAP

Posted on July 26, 2023

What is First Class Function? First Class Function in JavaScript

First-class functions are a concept in programming languages that refers to when functions in that language are treated like any other variable. For a language to support first-class functions, it needs to allow functions to be assigned to variables, passed as arguments, and returned from other functions, all without any restrictions.

JavaScript is one of those languages that treats functions as first-class citizens. This means that in JavaScript, you can do the following:

  1. Assign a function to a variable:
let greet = function() {
    console.log("Hello, world!");
}

// You can then invoke this function using that variable.

greet(); // This will output "Hello, world!" to the console.
Enter fullscreen mode Exit fullscreen mode
  1. Pass a function as an argument to another function:
function greet() {
    console.log("Hello, world!");
}

function callFunction(fn) {
    fn(); // Call the function
}

callFunction(greet); // This will output "Hello, world!" to the console.
Enter fullscreen mode Exit fullscreen mode
  1. Return a function from another function:
function createGreeter(name) {
    return function greet() {
        console.log("Hello, " + name + "!");
    };
}

let greeter = createGreeter("world");

greeter(); // This will output "Hello, world!" to the console.
Enter fullscreen mode Exit fullscreen mode
  1. Store functions in data structures:
let funcs = [function () { console.log("Hello"); }, function () { console.log("world!"); }];

// You can then invoke these functions.

funcs[0](); // This will output "Hello" to the console.
funcs[1](); // This will output "world!" to the console.
Enter fullscreen mode Exit fullscreen mode
  1. Functions can have properties and methods since they are objects:
function greet() {
    console.log("Hello, world!");
}

greet.language = "English"; // Assign property

console.log(greet.language); // Outputs: English
Enter fullscreen mode Exit fullscreen mode

In a nutshell, JavaScript allows us to use and manipulate functions just like any other object - we can store functions in variables, pass them around, create on the fly, etc. This ability to use functions as first-class objects with no restrictions is what makes JavaScript a very powerful and flexible language, especially for functional programming paradigms.

Thank you for reading, please follow me on Twitter, i regularly share content about Javascript, and React and contribute to Opensource Projects

Twitter-https://twitter.com/Diwakar_766

Github-https://github.com/DIWAKARKASHYAP

💖 💪 🙅 🚩
diwakarkashyap
DIWAKARKASHYAP

Posted on July 26, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related