Site icon JD Bots

How to Write a Function Inside Another Function in JavaScript

A card titled A Function Inside a Function, labelled JavaScript Basics, showing a sayHello function inside welcome and the output Hello, Sam! twice.

A Function Inside a Function: A helper that uses the outer function’s variables.

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();
}

See Functions and Closures on MDN.

Prerequisites

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

MistakeWhat happensDo this instead
Calling the inner function from outsideReferenceError: sayHello is not definedCall 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

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

Exit mobile version