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:
- 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.
- 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.
- 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.
- 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.
- 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
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
Top comments (0)