The Wayback Machine - https://web.archive.org/web/20240206163459/https://www.geeksforgeeks.org/javascript-nested-functions/
Open In App
Related Articles

JavaScript Nested functions

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In JavaScript, Functions within another function are called “Nested function.” These nested functions have access to the variables and parameters of the outer (enclosing) function, creating a scope hierarchy. A function can have one or more inner functions. 

Syntax:

// Outer function
function outerFunction() {
    // Nested function
    function nestedFunction() {
        // Function logic here
    }
    // Call the nested function
    nestedFunction();
    // Rest of the outer function logic
}
// Call the outer function
outerFunction();

Approach:

  • Write one function inside another function.
  • Make a call to the inner function in the return statement of the outer function.
  • Call it fun(a)(b) where a is a parameter to the outer and b is to the inner function.
  • Finally, return the combined output from the nested function.

Example 1: This example uses the approach discussed above. 

Javascript




function fun1(a) {
    function fun2(b) {
        return a + b;
    }
    return fun2;
}
function GFG_Fun() {
    console.log(fun1("A Online Computer Science Portal")
        (" GeeksforGeeks"));
}
GFG_Fun()


Output

A Online Computer Science Portal GeeksforGeeks

Example 2: This example uses the approach discussed above, but here the nested function is created differently than the previous one. 

Javascript




function fun1(a) {
    fun = function fun2(b) {
        return a + b;
    }
    return fun;
}
function GFG_Fun() {
    console.log(fun1("This is ")("GeeksforGeeks"));
}
GFG_Fun()


Output

This is GeeksforGeeks

Supported Browser: 

  • Google Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!


Last Updated : 08 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials