CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

Function Returning Function JavaScript: Explained with Examples

Shawpnendu Bikash Maloroy

June 22, 2024
Function Returning Function JavaScript: Explained with Examples
Spread the love

“Function Returning Function JavaScript” refers to a function that returns another function instead of a value (like int, string, or bool) when the user calls it. This is a common pattern in functional programming and allows for the creation of higher-order functions, currying, and function composition.

Now, let’s explore what it means for a function to return another function. In JavaScript, functions can return any type of data, including other functions. This means that you can write a function that, when called, gives you back another function.

Table of Contents

  • Why function returning function JavaScript is necessary?
  • Example: Simple Function Returning another Function
    • Code Explanation
  • Return an Anonymous Function
    • Output
  • How do I call a returned function immediately?
  • Example: How to Achieve Function Composition
  • Example: Creating a Logger Function to Showcase Another Use case of a Function Returning Function JavaScript
    • Output
    • Code Explanation
  • Example: Function Currying in JS
    • Code Explanation
  • Video Tutorial of JS Function Currying – Recommended
  • Conclusion
  • FAQ’s on Function Returning Function JavaScript
  • Can a function return a function in JavaScript?
  • Can you return multiple functions in JavaScript?
  • Can JavaScript run multiple functions at once?
  • Function Returning Function JavaScript: Are we able to use parameters?

Why function returning function JavaScript is necessary?

Using functions that return other functions can be very useful in several situations. Here are a few reasons why you have to use them:

  1. Encapsulation and Abstraction: They help to encapsulate logic and create more abstract and flexible code.
  2. Partial Application: They allow you to create partially applied functions, where some arguments are fixed and the returned function can be called with the remaining arguments.
  3. Closures: They enable the creation of closures, which can maintain state between function calls.
  4. Function Chaining: Enable you to arrange function calls based on necessity and for solution purposes. Mainly used for code reusability and easier code management.

Example: Simple Function Returning another Function

function outerFunction() {
    return function innerFunction() {
        console.log("Hello from the inner function!");
    };
}

// outerFunction returns innerFunction
const myFunction = outerFunction(); 

// Calling the returned innerFunction
myFunction(); 

Code Explanation

In this example:

  • outerFunction is defined and returns innerFunction.
  • When outerFunction is called, it returns innerFunction, which is then assigned to the variable myFunction.
  • myFunction is now a reference to innerFunction, so calling myFunction() executes the inner function, which logs “Hello from the inner function!”.

Return an Anonymous Function

<script>
   
   // function returning function javascript - Code Example
   function outerFunction() {
      return function innerFunction() {
         return 'Test Anonymous Function!';
      };
   }

   // innerFunction now assigned into myFunction
   const myFunction  = outerFunction(); 
   
   // check whthwer outerFunction return a function?
   console.log(myFunction);

</script>

Output

function returning function javascript- code example and output
Function returning function JavaScript- Code example and output

Now myFunction variable holds an anonymous function. Now print the variable into the console to see what myFunction holds now.

buymeacoffee

How do I call a returned function immediately?

In the above example, we hold a returned function in a constant variable first, and later on, we call the returned function. But we can call the returned function immediately instead of holding it in a variable first. Check out the below example to do it easily:

<script>
   
   // function returning function javascript - Code Example
   function outerFunction() {
      return function innerFunction() {
         return 'innerFunction Called !!';
      };
   }

   // Immediately call a returned function
   console.log(outerFunction()()); 
   // Output: innerFunction Called !!
   
</script>

Example: How to Achieve Function Composition

function add(a) {
    return function(b) {
        return a + b;
    };
}

const add5 = add(5);
console.log(add5(10)); // Outputs: 15
console.log(add5(20)); // Outputs: 25

const add10 = add(10);
console.log(add10(10)); // Outputs: 20
console.log(add10(20)); // Outputs: 30

In this example:

  • The “add" function takes an "a" parameter and returns a new function that takes “a” “b" parameter and returns the sum of “a" and “b".
  • add(5) returns a function that adds 5 to its input.
  • add5(10) outputs 15, and add5(20) outputs 25, demonstrating how the returned function works.

Example: Creating a Logger Function to Showcase Another Use case of a Function Returning Function JavaScript

Another practical use case is creating a custom logger function. Suppose you want to create a logging function that can log messages with different levels (info, warning, error).

<script>

   // An example of JavaScript function return function with parameters
   function genericLogger(level) {
      return function(message) {
      console.log(`[${level}] ${message}`);
      };
   }
   
   // Function returning function javascript example
   const informationLogger = genericLogger("INFO");
   informationLogger("An informational message.");

   // How to call a function in another function JavaScript
   const exceptionLogger = genericLogger("ERROR");
   exceptionLogger("An error message.");

</script>

Output

function returning function javascript - another use case
Function returning function JavaScript – Another use case
buymeacoffee

Code Explanation

In this example, genericLogger is a parent function that has a type of log parameter and returns a new function that has a log message parameter. The returned function takes a message and logs it along with the type of log.

Look at the above function named “genericLogger” very carefully. When a function returns another function, the returned function has the ability to remember the variables (level, in this case) from the scope in which it was created. This is known as closure or function currying.

Currying helps you avoid passing the same variable again and again.

Example: Function Currying in JS

function createCounter() {
  let count = 0;
  return function() {
    count++;
    return count;
  };
}

const counter = createCounter();
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2
console.log(counter()); // Output: 3

Code Explanation

In this example, createCounter creates a count variable and returns a function that increments and returns the count. The returned function remembers the count variable between calls because of the closure, or function currying.

Video Tutorial of JS Function Currying – Recommended

Conclusion

In conclusion of “function returning function javascript” – we clearly understood that functions that return other functions are a powerful feature in JavaScript. They allow you to create more flexible, reusable, and encapsulated code. By understanding this concept, you can write more advanced and efficient JavaScript programs. Whether you’re creating specific utility functions like multipliers and loggers or maintaining state with closures, functions returning functions can greatly enhance your coding toolkit.

Remember to practice with different examples to get comfortable with this concept. Happy coding!

FAQ’s on Function Returning Function JavaScript

Can a function return a function in JavaScript?

Yes, in JS, the system treats functions as objects, and you can pass them to other functions, return them from functions, and assign them to variables and properties. Don’t forget to examine our examples to understand more.

Can you return multiple functions in JavaScript?

JavaScript does not return more than one value or function by simply invoking the function. But you can achieve it by using arrays or objects. To return multiple values from a function, use an array. Create an array that is to be returned, and then call the array.

Can JavaScript run multiple functions at once?

Yes, in JS you can run multiple function at once. Look at the below example:

<script>
   
   // Demonestrate how to call multiple functions
   // at a time
   function func1() {
      console.log(‘func1 Called !!’);
      return function func2() {
         return ‘func2 Called !!’;
      };
   }
 
   
   console.log(func1()());
   // Output: func1 Called !!
   // Output: func1 Called !!
   
</script>

Function Returning Function JavaScript: Are we able to use parameters?

Yes, in JS, we can use function parameters in all outer functions as well as inner functions. Look at our examples. I hope you can understand all of our above examples of function-returning functions with parameters easily.

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

🏋️‍♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨‍✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
«Previous
Next»

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 5 Lesser-Known JavaScript Functions
    5 Lesser-Known JavaScript Functions to Boost Your Coding Efficiency
  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    🎮 Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! 🏆
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! 🐶
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright © 2024 CodersTechZone.com