How to receive multiple arguments ranging from and beyond the stated index and collect them into a single array to perform multiple actions using them.

If we have a function call which has to accept multiple values and perform actions using all of them at a time, then we can use this method to reduce the complexity of the code.

The _.restArguments() function is an inbuilt function in Underscore.js library of JavaScript which is used to find a version of the function which when invoked can receive all the arguments from and beyond the stated startIndex that is collected into a single array. The number of arguments to the function would be used to determine the startIndex when a definite value is not given.

<!DOCTYPE html> 
<html>
 
<head> 
<script src= 
"https://unpkg.com/underscore@1.11.0/underscore-min.js"> 
</script> 
</head>
 
<body> 
<script type="text/javascript"> 
		var call = 
			_.restArguments(function (who, whom) { 
				return who + ' ' + 
					_.initial(whom).join(', ') + 
					(_.size(whom) > 0 ? ', & ' : '') + 
					_.last(whom); 
			});
 
		// Calling the function above 
		// with its values 
		console.log( 
			call( 
				'She called', 'me', 'her', 'you.' 
			) 
		); 
</script> 
</body> 

Leave a comment

Your email address will not be published. Required fields are marked *