Example of a function

Simple example of a function in JavaScript. Note that it is generally considered best practice for function to have a single return, rather than two returns, one in the “then” clause and the other in the “else” clause of an if-then-else statement.

JavaScript

// Function that returns the smaller of 2 parameters
function minimum (a, b) {
	
	// Assume that a is the minimum until proven otherwise
	var theMinimum = a;

           // If b is less than a then it is the minimum
	if (b < a)
                   theMinimum = b;

	// Return the minimum value
	return theMinimum;
}

alert("minimum of 10 and 5 is " + minimum('10', '5'));
alert("minimum of 5 and 10 is " + minimum(5, 10));

/*
Try this:
1. Call the minimum function using two strings as parameters.
2. Call the minimum function using a number and a string.
*/