First-Class and Higher-Order Functions In JS: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the First-Class and Higher-Order Functions In JS.
First-Class and Higher-Order Functions In JS
In JavaScript, functions are first-class citizens, meaning that they can be treated like any other value in the language, such as numbers or strings. Functions can be assigned to variables, passed as arguments to other functions, and returned as values from functions.
Higher-order functions are functions that operate on other functions. In JavaScript, higher-order functions are used to manipulate functions and to create new functions. For example, you can use a higher-order function to wrap an existing function with some additional behavior.
Code For Higher-Order Function
For example:
function greet(name) {
return "Hello, " + name;
}
function say(func, name) {
console.log(func(name));
}
say(greet, "John");
Output
Hello, John
In this example, say
is a higher-order function because it takes greet
as an argument and calls it inside the body of the say
function.
Higher-order functions in JavaScript can also be used to create and return new functions. For example, you can use a higher-order function to create a custom function that has specific behavior.
This is a common technique in functional programming, where you create functions that are specialized versions of other functions.
For example:
function add(x) {
return function(y) {
return x + y;
};
}
const addFive = add(5);
console.log(addFive(3));
console.log(addFive(10));
Output
8
15
In this example, the add
function is a higher-order function because it returns a new function as its result. The returned function is a specialized version of the add
function that always adds 5
to its argument.
You can also use higher-order functions to create custom versions of built-in JavaScript functions like map
, filter
, and reduce
. These functions allow you to apply a function to each element in an array and return a new array with the results.
For example:
const numbers = [1, 2, 3, 4, 5];
const double = numbers.map(function(x) {
return x * 2;
});
console.log(double);
Output
[2, 4, 6, 8, 10]
In this example, map
is a higher-order function because it takes a function as an argument and applies it to each element in the array. The double
array is the result of applying the x * 2
function to each element in the numbers
array.
Conclusion
If you liked this post First-Class and Higher-Order Functions In JS, then please share this with your friends and make sure to bookmark this website for more awesome content.