A function inside a function in JavaScript is called a nested function. You define it by declaring a function within another function's body, and it can access the outer function's variables. Here is the shortest working example: function outer() { function inner() { return 'hi'; } return inner(); }. Nested functions are useful for encapsulation, closures, and keeping helper logic private. This guide walks through creating, calling, and returning nested functions, plus common pitfalls.
What You'll Need
- A modern web browser (Chrome, Firefox, Edge, Safari) with developer tools, or Node.js installed for running scripts from the terminal.
- A code editor such as VS Code, or any plain text editor.
- Basic familiarity with JavaScript syntax: variables, function declarations, and return statements.
Step-by-Step
- Open a JavaScript environment. In a browser, press F12 (or right-click and choose Inspect) and open the Console tab. Alternatively, create a file named
nested.jsand run it withnode nested.js. The console lets you type and execute code immediately. - Declare an outer function. Type
function outer() { }. Everything inside the curly braces is the function body. This is the container for your nested function. - Declare an inner function inside the outer body. Add
function inner() { return 'Hello from inner'; }insideouter. The inner function is now nested. It is not accessible from outsideouterunless you return it or expose it. - Call the inner function from within the outer function. Add
return inner();after the inner declaration. The full code is:function outer() { function inner() { return 'Hello from inner'; } return inner(); } - Invoke the outer function. Type
outer();in the console. It returns'Hello from inner'. The inner function ran because the outer function called it. - Try calling the inner function directly. Type
inner();. You will get a ReferenceError: inner is not defined. This confirms the inner function is scoped to the outer function and cannot be called globally. - Return the inner function instead of calling it. Change the outer function to
function outer() { function inner() { return 'Hello again'; } return inner; }(note: no parentheses afterinner). Nowconst myFunc = outer();stores the inner function in a variable. Call it withmyFunc();to get the string. This pattern is the basis of closures. - Use a nested function to access outer variables. Modify the outer function to accept a parameter:
function greet(name) { function inner() { return 'Hello, ' + name; } return inner(); }. Callgreet('Sam');and it returns'Hello, Sam'. The inner function readsnamefrom the outer scope. - Test with an arrow function (optional). You can also nest arrow functions:
const outer = () => { const inner = () => 'Arrow nested'; return inner(); };. The same scoping rules apply. - Verify the scope chain. In the console, after running the closure example, check that
myFuncstill has access to variables fromoutereven afterouterhas finished executing. This is normal JavaScript behavior and is why nested functions are powerful for data privacy.
Common Mistakes
- Calling the inner function from outside. The inner function is not global; you must call it from within the outer function or return it and call the returned reference.
- Forgetting the return statement. If you define an inner function but never call or return it, it does nothing. The outer function must invoke it or return it for it to be useful.
- Confusing function declaration with function expression. A nested function declaration is hoisted within the outer function, but a function expression assigned to a variable is not. This affects when you can call it.
- Overusing nesting. Deeply nested functions (three or more levels) become hard to read. Keep nesting shallow and extract helpers to the module scope when they do not need outer variables.
- Assuming
thisbehaves the same. Nested regular functions have their ownthisbinding (usuallyundefinedin strict mode), which can break code that relies on the outerthis. Use arrow functions or.bind()if you need the outer context.
Tips
- Use nested functions to hide implementation details. Only expose what the outer function returns.
- Name inner functions descriptively even though they are scoped locally; it helps debugging stack traces.
- Combine nested functions with closures to create factory functions that remember state.
- If you need the inner function in multiple places, define it at the module level instead of nesting it repeatedly.
- Remember that every call to the outer function creates a new inner function instance, which can affect memory if you create many closures.
Troubleshooting
If you see ReferenceError: inner is not defined, you are trying to call the inner function from outside its scope. Move the call inside the outer function or return the inner function and call the returned value.
If the outer function returns undefined, check that you actually return the result of the inner function or the inner function itself. A common slip is writing inner; instead of return inner(); or return inner;.
If variables from the outer function are unexpectedly undefined inside the inner function, confirm the order of declaration: the inner function can access variables declared before it runs, but if you reassign them later, the inner function sees the latest value at call time.
If you get a syntax error, check for missing braces or parentheses. Nested functions require balanced curly braces. Use the console's error message to locate the line.
If this is not what you expect inside a nested function, switch to an arrow function for the inner function or capture this in a variable (e.g., const self = this;) before the inner function.
Frequently Asked Questions
Can a function inside a function be called from outside?
Not directly. The inner function is scoped to the outer function. To use it outside, return it from the outer function and call the returned reference.
What is the difference between a nested function and a closure?
A nested function is simply a function defined inside another. A closure is formed when a nested function accesses variables from its outer scope and survives after the outer function returns. Every closure involves a nested function, but not every nested function creates a closure.
Are nested functions hoisted?
Function declarations inside a function are hoisted to the top of that function's scope, so you can call them before their declaration line within the same outer function. Function expressions assigned to variables are not hoisted in the same way.
Can I nest arrow functions?
Yes. Arrow functions can be nested just like regular functions. They inherit this from the enclosing scope, which often makes them preferable for inner functions.
Does nesting functions affect performance?
Defining a nested function on every call of the outer function creates a new function object each time, which has a small cost. For most code this is negligible. If performance is critical, define the helper outside the outer function when it does not need outer variables.
Can a nested function modify outer variables?
Yes, if the outer variable is declared with let or var (or is a parameter), the inner function can reassign it. Variables declared with const cannot be reassigned, but their properties can be mutated if they are objects.