Anonymous Functions

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

Anonymous Functions

Going back to our previous example, the functions add and multiply are only referred to once, in each call to combineAll. Furthermore, if we stick to that pattern, we will need to create a new function for each new combination behavior we desire (e.g., concatenation) just so we can pass it to combineAll. That seems like too much overhead for such a simple thing.

Thankfully, we don't actually need to declare each of these functions. We don't even need to come up with names for them. JavaScript allows us to create functions on the spot, any time we need a function that will only be used in that location.

The syntax is rather compact:

function (arg1, arg2) {
	//function statements here
	}

Because functions created this way don't have names, they are aptly called anonymous functions.

Let's revisit our previous example and use anonymous functions to replace the single-use functions we declared:

Code Sample:

AdvancedTechniques/Demos/anon-func-arguments.html
---- C O D E   O M I T T E D ----

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

The highlighted code represents the three anonymous functions. The first two replace where we previously had add and multiply functions defined. The third anonymous function is used to concatenate the integers into a comma separated list.

Next