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
Selected Reading
JavaScript outsider function call and return the result
In JavaScript, you can call functions from outside their defining scope by using the return keyword to return inner functions. This creates closures that maintain access to outer variables.
Syntax
function outerFunction() {
// Outer variables
var outerVar = value;
// Inner function
var innerFunction = function() {
// Can access outerVar
return result;
}
// Return inner function for outside access
return innerFunction;
}
var result = outerFunction(); // Get the inner function
result(); // Call the inner function
Example
var subtractMethod = function () {
var firstValue = 1000, thirdValue = 200;
var divideMethod = function () {
var secondValue = 500;
console.log("The result of divideMethod() = " + (firstValue/secondValue));
return (firstValue - secondValue);
}
return divideMethod; // Return inner function
}
var result = subtractMethod(); // Get the inner function
console.log("The result of subtractMethod() = " + result()); // Call it
The result of divideMethod() = 2 The result of subtractMethod() = 500
How It Works
The outer function subtractMethod returns the inner function divideMethod. When called from outside, the inner function still has access to the outer function's variables (firstValue) due to JavaScript closures.
Practical Example
function createCalculator(initialValue) {
var value = initialValue;
var calculator = function(operation, number) {
if (operation === 'add') {
value += number;
} else if (operation === 'multiply') {
value *= number;
}
return value;
}
return calculator;
}
var calc = createCalculator(10);
console.log(calc('add', 5)); // 15
console.log(calc('multiply', 3)); // 45
15 45
Key Points
- Inner functions maintain access to outer variables even after the outer function completes
- Use
returnto expose inner functions to the outside scope - This pattern creates closures, useful for data privacy and function factories
Conclusion
Returning inner functions allows outside access while preserving closure over outer variables. This pattern is fundamental for creating modular, reusable JavaScript code.
Advertisements
