JavaScript functions can return another function as its value, which is known as a “higher-order function”. This feature allows for more flexible and powerful code and is commonly used in functional programming to create closures and implement currying.
The syntax for returning a function from another function in JavaScript is as follows:
function outerFunction() {
// code here
return function innerFunction() {
// code here
};
}
In this syntax, outerFunction
is the enclosing function that returns the innerFunction
. The innerFunction
is defined within the outerFunction
and can access its local variables and parameters. When outerFunction
is called, it returns the innerFunction
as its result.
JavaScript function return function example
Simple example code.
function add(x) {
return function(y) {
return x + y;
}
}
const addTwo = add(2);
console.log(addTwo(3));
Output: 5
Another example
function greetingMaker(name) {
function greet() {
console.log(`Hello, ${name}!`);
}
return greet;
}
const greetJohn = greetingMaker('John');
greetJohn(); // logs "Hello, John!"
const greetSarah = greetingMaker('Sarah');
greetSarah(); // logs "Hello, Sarah!"
Output:
Or you can do it with the function:
function createCounter() {
let count = 0;
return function() {
count++;
console.log(count);
}
}
const counter1 = createCounter();
const counter2 = createCounter();
counter1(); // logs 1
counter1(); // logs 2
counter1(); // logs 3
counter2(); // logs 1
counter2(); // logs 2
Comment if you have any doubts or suggestions on this JS function return topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version