Is this really possible.

Yes.

function a(x) {    // <-- function
  function b(y) { // <-- inner function
    return x + y; // <-- use variables from outer scope
  }
  return b;       // <-- you can even return a function.
}
console.log(a(3)(4));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Answer from kennytm on Stack Overflow
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Functions
Functions - JavaScript | MDN
A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access. On the other hand, the parent function (and any other parent scope) does not have access to the variables and functions defined ...
Discussions

How to use the same function (which is created inside a function) inside another function?
If a function is declared within another function and you then need that inner function elsewhere you should move it to a global scope. Even if it was possible to call that inner function in another function it would be bad design and go against proper encapsulation patterns. More on reddit.com
🌐 r/learnjavascript
11
1
October 28, 2024
javascript - Should I place functions that are only used in one other function, within that function? - Software Engineering Stack Exchange
In JavaScript, big file-spanning functions often fulfill the role of classes because the language doesn't provide any other scope-limiting mechanism. Certainly helper functions should go inside such quasi-classes, not outside them. More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
August 6, 2014
Using a function in another function
I’m stuck!!! I’m trying my newfound coding skills on a home project and I have a 3 functions finding a total of 3 different input values. Now I want to use the totals inside those functions in another function. My first thought was to use a global variable of subTotal but the new function ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
8
0
January 13, 2021
JavaScript Nested function - Stack Overflow
It's perfectly normal in JavaScript (and many languages) to have functions inside functions. More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-nested-functions
JavaScript Nested functions - GeeksforGeeks
A nested function is a function defined inside another function in JavaScript.
Published: July 12, 2025
🌐
Reddit
reddit.com › r/learnjavascript › how to use the same function (which is created inside a function) inside another function?
r/learnjavascript on Reddit: How to use the same function (which is created inside a function) inside another function?
October 28, 2024 -

Hello everyone.

I am asking because I am curious (not that I need the answer right now ((as I managed to solve my problem by using the parent function instead of using the child function))).

Let's say you have a function inside a function but you want the use the same inner(child) function inside a another function. As this inner function has the function scope (instead of global scope) you won't be using this inner function directly inside another function. Soo, what are the possible methods for this?

Example:

function outerFunction () {

function innerFunction();

}

function anotherFunction () {

function innerFunction();

}

Top answer
1 of 3
8
If a function is declared within another function and you then need that inner function elsewhere you should move it to a global scope. Even if it was possible to call that inner function in another function it would be bad design and go against proper encapsulation patterns.
2 of 3
7
Everyone else is right with their advice, so you should take this on board. However it IS possible to call a function declared inside a function from outside providing you find a way to create a reference. Some examples: 1: Assigning the function let inner; function outer() { inner = function () { console.log("Inner"); } } outer(); inner(); // Logs ‘Inner’ This is horribly fragile and also pointless. Just define the inner function in the outer scope instead. Because inner is not defined until outer is called, there is a whole load of possible sequencing bugs (made worse if outer could throw in any way before assigning the function) 2: Returning a function function outer() { function inner() { console.log("Inner"); } return inner; } const inner = outer(); inner(); // Logs ‘Inner’ const inner2 = outer(); inner2(); // Logs ‘Inner’ inner === inner2; // false This is better, but still mostly pointless in this case. When outer is called, it creates a new function and returns it. That means each call to outer generates a new function with a unique function pointer. There may be some limited cases where this is useful. 3: Returning a function (with args) function min(x) { return function (y) { return y >= x; } } const atLeast3 = min(3); atLeast3(2); // false atLeast3(4); // true const atLeast5 = min(5); atLeast5(2); // false atLeast5(4); // false atLeast5(8); // true Now we have something that may actually be useful. By passing arguments to the outer function we can return a function who’s behaviour is based on those arguments. In this case, comparing a number. This is not something to aim for - it’s a tool and should be used sensibly. 4: IIFE (Immediately Invoked Function Expression) const inner = (function() { return function() { console.log("Inner"); } })(); inner(); // Logs ‘Inner’ This is used far less these days, and I would suggest that it’s rarely the right choice in 2024. Here, a function is created, wrapped in parentheses and then immediately called. Essentially, its #2 or #3 called immediately, with no reference to the outer function left lying around. 5: Internal state function counter() { let count = 0; return function() { count++; return count; }; } const count = counter(); count(); // 1 count(); // 2 const count2 = counter(); count2(); // 1 Variables defined within a function are scoped to that function, and if you return functions(s) that modify those variables then it will modify them in the scope it was created. In this case, each time we call counter we create a new counter that starts at 0 and remembers it’s own state. Note: I’ve avoided using “arrow functions” here for demonstration. It would be very common to return an arrow function in most of these examples, e.g. function outer() { return () => console.log("Inner"); }
Top answer
1 of 6
45

I'm generally in favor of nested functions, especially in JavaScript.

  • In JavaScript, the only way to limit a function's visibility is by nesting it inside another function.
  • The helper function is a private implementation detail. Putting it at the same scope is akin to making a class' private functions public.
  • If it turns out to be of more general use, it's easy to move out, because you can be confident the helper is currently only used by that one function. In other words, it makes your code more cohesive.
  • You can often eliminate parameters, which makes the function signature and implementation less verbose. This is not the same thing as making variables global. It's more like using a class member in a private method.
  • You can give the helper functions better, simpler names, without worrying about conflicts.
  • The helper function is easier to find. Yes, there are tools that can help you. It's still easier to just move your eyes up the screen a bit.
  • Code naturally forms a sort of tree of abstraction: a few general functions at the root, branching out into several implementation details. If you use an editor with function folding/collapsing, nesting creates a hierarchy of closely-related functions at the same level of abstraction. That makes it very easy to study the code at the level you need and hide the details.

I think a lot of opposition comes from the fact that most programmers were either brought up in a C/C++/Java tradition, or were taught by someone else who was. Nested functions don't look natural because we weren't exposed to them much when we were learning to program. That doesn't mean they aren't useful.

2 of 6
22

You should put it at global scope, for several reasons.

  • Nesting a helper function into the caller increases the length of the caller. Function length is almost always a negative indicator; short functions are easier to understand, to memorize, to debug and to maintain.

  • If the helper function has a sensible name, reading that name is enough without needing to see the definition nearby. If you do need to see the helper definition in order to understand the caller function, then that caller is doing too much, or is working on too many levels of abstraction simultaneously.

  • Having the helper globally available allows other functions to call it if it turns it to be generally useful after all. If the helper isn't available, you're tempted to cut and paste it, or to forget it and reimplement it, poorly, or to make another function longer than it has to be.

  • Nesting the helper function increases the temptation to use variables from the caller's scope without declaration, so that it becomes unclear what the inputs and outputs of the helper are. If a function doesn't clearly state what data it operates on and what effects it has, it is usually a sign of unclear responsibilities. Declaring the helper ass a standalone function forces you to know just what it actually does.

Edit

That turned out to be a more controversial question than I thought. To clarify:

In JavaScript, big file-spanning functions often fulfill the role of classes because the language doesn't provide any other scope-limiting mechanism. Certainly helper functions should go inside such quasi-classes, not outside them.

And the point about easier reuse presupposes that if a subroutine does become more widely used, you are willing to move it out of place altogether and put it in appropriate place, e.g. a string utility library or into your global configuration registry. If you don't want to order your code like that, then you might as well nest the subroutine, just like you would do with a normal Method Object in a more "blocky" language.

🌐
W3Schools
w3schools.com › js › js_functions.asp
JavaScript Function Study Path
A JavaScript callback is a function passed as an argument to another function, which is then executed (or "called back") at a later point in time to complete a specific task. ... How this works (especially inside objects).
Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Using a function in another function - Curriculum Help - The freeCodeCamp Forum
January 13, 2021 - I’m stuck!!! I’m trying my newfound coding skills on a home project and I have a 3 functions finding a total of 3 different input values. Now I want to use the totals inside those functions in another function. My first thought was to use a global variable of subTotal but the new function ...
Top answer
1 of 8
166

Functions are another type of variable in JavaScript (with some nuances of course). Creating a function within another function changes the scope of the function in the same way it would change the scope of a variable. This is especially important for use with closures to reduce total global namespace pollution.

The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function:

function foo(doBar)
{
  function bar()
  {
    console.log( 'bar' );
  }

  function baz()
  {
    console.log( 'baz' );
  }

  window.baz = baz;
  if ( doBar ) bar();
}

In this example, the baz function will be available for use after the foo function has been run, as it's overridden window.baz. The bar function will not be available to any context other than scopes contained within the foo function.

as a different example:

function Fizz(qux)
{
  this.buzz = function(){
    console.log( qux );
  };
}

The Fizz function is designed as a constructor so that, when run, it assigns a buzz function to the newly created object. That is, you'd use it like this:

const obj = new Fizz();
obj.buzz();

or more concisely (if you don't need to keep the object after calling buzz):

new Fizz().buzz();
2 of 8
43

It is called closure.

Basically, the function defined within other function is accessible only within this function. But may be passed as a result and then this result may be called.

It is a very powerful feature. You can see more explanation here:

javascript_closures_for_dummies.html mirror on Archive.org

🌐
Tumult
forums.tumult.com › using javascript with hype › function library
Calling one function from another - function scope - Function Library - Tumult Forums
May 4, 2016 - I am sure this is blindingly obvious but… How does one call a function from a second function? If ‘nested’ within the current function it is fine - e.g. functionmain() { //do something; functionsub() // call secondary function; function functionsub() { //do something else to call above; ...
🌐
SheCodes
shecodes.io › athena › 1697-can-i-place-a-function-in-another-function-in-javascript
[JavaScript] - Can I Place a Function in another Function in JavaScript?
Yes, a function can be placed in another function in JavaScript. Learn what is nested function and example code provided.
Top answer
1 of 5
148

Yes, what you have there is right. Some notes:

  • bar is created on every call to the function foo, but:
    • On modern browsers this is a very fast process. (Some engines may well only compile the code for it once, and then reuse that code with a different context each time; Google's V8 engine [in Chrome and elsewhere] does that in most cases.)
    • And depending on what bar does, some engines may determine that they can "inline" it, eliminating the function call entirely. V8 does this, and I'm sure it's not the only engine that does. Naturally they can only do this if it doesn't change the behavior of the code.
  • The performance impact, if any, of having bar created every time will vary widely between JavaScript engines. If bar is trivial, it will vary from undetectable to fairly small. If you're not calling foo thousands of times in a row (for instance, from a mousemove handler), I wouldn't worry about it. Even if you are, I'd only worry about it if I saw a problem on slower engines. Here's a test case involving DOM operations, which suggests that there is an impact, but a trivial one (probably washed out by the DOM stuff). Here's a test case doing pure computation which shows a much higher impact, but frankly even, we're talking a difference of microseconds because even a 92% increase on something that takes microseconds to happen is still very, very fast. Until/unless you saw a real-world impact, it's not something to worry about.
  • bar will only be accessible from within the function, and it has access to all variables and arguments for that call to the function. This makes this a very handy pattern.
  • Note that because you've used a function declaration, it doesn't matter where you put the declaration (top, bottom, or middle — as long as it's at the top level of the function, not inside a flow control statement, which is a syntax error), it gets defined before the first line of step-wise code is run.
2 of 5
16

This is what closures are for.

var foo = (function () {
  function bar() {
    // perform task 3
  };

  function innerfoo (a) { 
    if (/* some cond */ ) {
      // perform task 1
      bar();
    }
    else {
      // perform task 2
      bar();
    }
  }
  return innerfoo;
})();

Innerfoo (a closure) holds a reference to bar and only a reference to innerfoo is returned from an anonymous function which is called only once to create the closure.

Bar is not accessible from the outside this way.

🌐
EDUCBA
educba.com › home › software development › software development tutorials › javascript tutorial › javascript nested functions
Javascript Nested Functions | 4 Examples of Javascript Nested Functions
June 19, 2023 - JavaScript (JS) has allowed nested functions without any errors. JS allows anonymous functions also inside an outer function. Child function can access all values global, local, and parent.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
TutorialsPoint
tutorialspoint.com › javascript › javascript_nested_functions.htm
JavaScript - Nested Functions
Prior to JavaScript 1.2, function definition was allowed only in top level global code, but JavaScript 1.2 allows function definitions to be nested within other functions as well.
🌐
TutorialsPoint
tutorialspoint.com › javascript › javascript_builtin_functions.htm
JavaScript Built-in Functions Reference
Here, you can find all the JavaScript's built-in methods on the following classes: The Number object contains only the default methods that are part of every object's definition.
🌐
LinkedIn
linkedin.com › pulse › mastering-javascript-nested-functions-closures-javascript-code-yrvuc
Mastering JavaScript: Nested Functions and Closures
November 21, 2023 - In JavaScript, nested functions refer to the practice of defining a function inside another function. This concept leverages the idea of scope, where each function has access to its own scope and the scope of the functions that contain it.
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Functions inside objects - Curriculum Help - The freeCodeCamp Forum
October 29, 2021 - How can i call a function if that whole function is stored in an object? A challenge suggested that objects can store functions, i tried calling a function which was inside an object, but didn’t work. So what is the use of it being stored in an object? Exemple: Const obj = { func1: function test(){return 3>5;} }; Thank you.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Function
Function - JavaScript | MDN
Represents the arguments passed to this function. For strict, arrow, async, and generator functions, accessing the arguments property throws a TypeError. Use the arguments object inside function closures instead.
🌐
Substack
substack.com › @thepursuitofcompounding › note › c-241719765
The Pursuit of Compounding (@thepursuitofcompounding): "Two cars. Two bags. Same function. Extraordinarily different economics. The commodity holds your items. The compounder holds your status. The difference? Intangibles. The most powerful asset on a balance sheet may be the one that doesn't appear on it."
April 15, 2026 - Two cars. Two bags. Same function. Extraordinarily different economics. The commodity holds your items. The compounder holds your status. The difference? Intangibles. The most powerful asset on a balance sheet may be the one that doesn't appear on it.