You can write a function inside another function. The inner function can only be called from inside the outer one, and it can use the outer function’s variables and parameters. MDN calls this a closure.
Every command and output on this page is real, run with Node.js 26.13.1 on macOS.
Syntax
Syntax
function outer() {
function inner() {
// inner can use outer’s variables
}
inner();
}
outer: the function you call from the rest of your code.inner: a function written inside it. Only code insideoutercan call it.inner(): the call, insideouter.
See Functions and Closures on MDN.
Prerequisites
- Node.js, to run the example. Install it from the Node.js download page.
The Example
A welcome function with a helper inside it, sayHello, that greets the person whose name was passed to welcome. The file is welcome.js.
Step 1: Write the Code
welcome.js
function welcome(name) {
function sayHello() {
console.log("Hello, " + name + "!");
}
sayHello();
sayHello();
}
welcome("Sam");
sayHello has no parameter of its own, but it uses name, the outer function’s parameter. welcome calls it twice.
Step 2: Run It
Terminal
node welcome.js
Output
Hello, Sam!
Hello, Sam!
Both calls printed the name that was passed to welcome.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Calling the inner function from outside | ReferenceError: sayHello is not defined | Call it inside the outer function |
FAQ
Why put a function inside another one?
To keep a helper next to the only code that uses it, and let it use that code’s variables without passing them in.
Conclusion
A function inside another function is a private helper: only the outer function can call it, and it can use the outer function’s variables.
Additional Resources
- Functions (MDN)
- Closures (MDN)
- Run Node.js scripts from the command line (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
