Anonymous Functions

Overview


Anonymous functions are functions that are not assigned a name. They are used only once in code.

Anonymous Function as Argument


Functions can be arguments to other functions. (see function arguments) As an example consider the following code, which filters an array for numbers that are less than 5.


let list = [1,2,3,4,5,6,7,8,9,10];

function lessThan5(arg){
	return arg < 5
}

let result = list.filter(lessThan5);
            	

The lessThan5 function is passed to the filter method of array, which is used to generate the result. However, the lessThan5 function is used only once, for this purpose alone. Declaring a function for use only once can be a bit excessive.

Anonymous functions lets you define the function without a name directly as an argument to the filter function.


let list = [1,2,3,4,5,6,7,8,9,10];

let result = list.filter(function(p){
	return p<5;
});
            	

This code can be simplied even further by using arrow functions.


let list = [1,2,3,4,5,6,7,8,9,10];

let result = list.filter(p=>p<5);
            	

Immediate Execution


Anonymous functions can be declared and executed immediately in the following manner.


(function(){
	alert('hello world')
})();
				

Note that the function is declared within parentheses, and the the parentheses at the end immediately calls the declared function.


(async function(){
	await $url('http://server/');
})();
				

This can be shortened again using arrow functions.


(async ()=>{
	await $url('http://server/');
})();