Function Arguments

Overview

Arguments are the inputs to a function. They are declared in the function definition


	function multiply(a, b){
	return a*b;
	}
	
	let result = multiply(5,10);
	


An error will not occur if the user enters in less arguments than declared in the function declaration. Any arguments not passed in the function call are given a special value called "undefined".


	function multiply(a, b){
	if(b===undefined) b= 10;
	return a*b;
	}
	
	//this is legal
	let result = multiply(5);
	


Default Arguments

Default values can be assigned to function arguments in the function declaration. The following will assign b to be equal to 10 if it is not provided in the function call.


	function multiply(a, b=10){
	return a*b;
	}
	



	let result1 = multiply(5,2);
	//result1 will be equal to 10
	
	let result2 = multiply(5);
	//result2 will be equal to 50
	
Try it!

Variable Number of Arguments




	function multiply(){
	let result = 1;
	for(let arg of arguments) result = result * arg;
	return result;
	}
	
	let result = multiply(2,2,3,4,5);
	
Try it!

Functions as Arguments to Functions

Specify the Name and Input dataset
Functions can be used like any other piece of data or variable. For example, a function can be passed to another function, as a parameter. This may seem like a fairly obscure fact that is not that useful, but it turns out to be incredibly useful in data querying and transformations.


	let data = [1,2,3,4,5];
	let answer = [];
	
	for(let number of data){
	if(number>3) answer.push(number);
	}
	
	
Try it!



This code effectively filters the list of numbers for numbers that are greater than 3.

Lets imagine that we put the filter condition in a function as follows.


	let data = [1,2,3,4,5];
	let answer = [];
	let condition = function(number){
	if(number>3) return true;
	else return false;
	}
	
	for(let number of data){
	if(condition(number)) answer.push(number);
	}
	
	
Try it!


	let data = [1,2,3,4,5];
	let answer = [];
	let condition = function(number){
	if(number>3) return true;
	else return false;
	}
	
	let filter = function(data, condition){
	let answer = [];
	for(let item of data){
	if(condition(item)) answer.push(item);
	}
	return answer;
	}
	
	let filtered = filter(data, condition);
	
	
Try it!



Once we have a filter function defined as above, we can now filter an array very simply.


	let filtered = filter([1,2,3,4,5], p=>p>3);
	
Try it!



As an additional simplification, the filter function is defined on the array object, so that we can do the following.


	let filtered = [1,2,3,4,5].filter(p=>p>3);
	
Try it!