Nested Functions
Last Updated: 22nd October 2025
A nested function is a function inside another function.
The inner function can only be accessed inside the outer function.
Hinglish Tip 🗣: Nested function ka matlab hota hai — ek function ke andar doosra function. Inner function bahar se call nahi hota, sirf outer function ke andar hi use hota hai.
✏️ Syntax
function outerFunction() {
console.log("This is the outer function");
function innerFunction() {
console.log("This is the inner function");
}
innerFunction(); // Call inner function here
}
outerFunction();
📚 Key Points
- The inner function can access variables of the outer function.
- But the outer function cannot access variables of the inner function.
- Useful in data hiding, closures, and modular programming.
function greetUser() {
let name = "Ravi";
function showMessage() {
console.log("Hello " + name + "! 👋");
}
showMessage();
}
greetUser();
Hinglish Tip 🗣: Inner function outer variable ko use kar sakta hai — yehi concept baad me Closure me kaam aayega.
Need of Nested Functions?
- To group related logic together.
- To limit variable scope (data hiding).
- Used in closures, callback patterns, and modular design.
💡 Quick Practice
- Create a function calculate() with an inner function add() that adds two numbers.
- Try to call the inner function from outside — observe what happens.
- Modify your code to print both messages (“outer called”, “inner called”).
- Exercise Set 1
- Exercise Set 2