Functions Returning Functions In JS

Functions Returning Functions In JS: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Functions Returning Functions In JS.

Functions Returning Functions In JS

In JavaScript, functions can return other functions as their result. This allows you to create dynamic, reusable functions that can be customized at runtime.

Code For Function Returning Function

For example:

function createGreeting(greeting) {
  return function(name) {
    return greeting + ", " + name;
  };
}

const sayHello = createGreeting("Hello");
console.log(sayHello("John"));

const sayHi = createGreeting("Hi");
console.log(sayHi("Jane"));

Output

Hello, John

Hi, Jane

In this example, the createGreeting function is a higher-order function that returns a new function as its result. The returned function is a specialized version of the createGreeting function that always returns a greeting with a specified greeting.

Functions that return functions can be used to create reusable, composable functions that can be customized at runtime. This is a common technique in functional programming, where you write functions that are generalized versions of other functions.

Higher-Order Function Returning A Function

For example:

function createAdder(x) {
  return function(y) {
    return x + y;
  };
}

const addFive = createAdder(5);
console.log(addFive(3));
console.log(addFive(10));

Output

8

15

In this example, the createAdder function is a higher-order function that returns a new function as its result. The returned function is a specialized version of the createAdder function that always adds a specified value to its argument.

Conclusion

If you liked this post Functions Returning Functions In JS, then please share this with your friends and make sure to bookmark this website for more awesome content.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment