First-class Functions in Javascript
Introduction
- First-class functions mean functions are treated like any other variable or value
- A programming language is said to have First-class functions when functions in that language are treated like any other variable
- A function can be passed as an argument to other functions
- A function can be returned by another function and can be assigned as a value to a variable
Assign function to a variable:
In JavaScript, any functions can be assigned to a variable
//Example const message = function () { console.log("message"); } // Invoke it using the variable message();
Pass a function as an Argument
In JavaScript, we can pass a function as an argument to another function
//Example: function sayHello() { return "Hello, "; } function greeting(helloMessage, name) { console.log(helloMessage() + name); } // Pass `sayHello` as an argument to `greeting` function greeting(sayHello, "JavaScript!");
Return a function
A function can return another function
unction sayHello() { return function () { console.log("Hello!"); } }