Nested Functions

Contact Us or call 1-877-932-8228
Nested Functions

Nested Functions

Since functions in JavaScript are just one more type of object, we can create a function inside another function. These are called nested functions or inner functions.

The example below shows how to create and use a function inside another one:

Code Sample:

AdvancedTechniques/Demos/inner-functions.html
---- C O D E   O M I T T E D ----

	var values = [5, 2, 11, -7, 1];
		
	function combineAll(nums, initialValue, operator) {
		var runningResult = initialValue;
		for (var i=0; i < nums.length; i++) {
			runningResult = calculate(nums[i]); 
		}
		return runningResult;
		
		function calculate(num) {
			switch (operator.toLowerCase()) {
				case "+" :
					return runningResult + num;
				case "x" :
					return runningResult * num;
				case "*" :
					return runningResult * num;
				case "a" :
					return runningResult + ", " + num;
			}
		}
	}
		
	var sum = combineAll(values, 0, "+");
	var product = combineAll(values, 1, "x");
	var list = combineAll(values, 1, "a");
			
	alert("Sum: " + sum);
	alert("Product: " + product);
	alert("Number List: " + list);
---- C O D E   O M I T T E D ----

We will see more important uses of inner functions when we look at private members. For the time being, just notice how calculate() has access to operator and runningResult, which are scoped to the combineAll() function.

Next