Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to define functions inside a function body in JavaScript?
To define functions inside a function body in JavaScript, you can use nested function declarations or function expressions. This creates closures that have access to the outer function's scope.
Basic Nested Function
Functions declared inside another function are only accessible within that parent function:
function outerFunction() {
function innerFunction() {
console.log("Hello from inner function!");
}
innerFunction(); // Call the nested function
}
outerFunction();
Hello from inner function!
Using Closures
Inner functions can access variables from their parent scope, creating closures:
function createCounter() {
let count = 0;
function increment() {
count++;
console.log("Count:", count);
}
function decrement() {
count--;
console.log("Count:", count);
}
return { increment, decrement };
}
const counter = createCounter();
counter.increment();
counter.increment();
counter.decrement();
Count: 1 Count: 2 Count: 1
Immediately Invoked Function Expression (IIFE)
You can create a function that immediately returns another function:
const myFunction = (function() {
function display() {
console.log("Display function called");
}
function innerDisplay(condition) {
if (condition) {
console.log("Condition is true");
display();
} else {
console.log("Condition is false");
display();
}
}
return innerDisplay;
})();
myFunction(true);
myFunction(false);
Condition is true Display function called Condition is false Display function called
Function Expressions Inside Functions
You can also use function expressions to define nested functions:
function calculator() {
const add = function(a, b) {
return a + b;
};
const multiply = function(a, b) {
return a * b;
};
return {
addition: add,
multiplication: multiply
};
}
const calc = calculator();
console.log(calc.addition(5, 3));
console.log(calc.multiplication(4, 7));
8 28
Key Benefits
- Encapsulation: Inner functions are private to the outer function
- Closure Access: Inner functions can access outer function variables
- Data Privacy: Variables in the outer function are protected from global scope
Conclusion
Defining functions inside functions creates closures that provide encapsulation and data privacy. This pattern is commonly used for creating modules, factories, and maintaining private state in JavaScript applications.
