Get Programming with JavaScript - Listing 7.05
Listing 7.05 - Using Math.min and Math.max
JS Bin
var showSmaller = function (num1, num2) {
var smaller = Math.min(num1, num2);
var larger = Math.max(num1, num2);
console.log(smaller + " is smaller than " + larger);
};
showSmaller(12, 3);
showSmaller(-10, 3);
Further Adventures
Listing 7.05 - Using Math.min and Math.max - Task 1
- Try out some different arguments.
var showSmaller = function (num1, num2) {
var smaller = Math.min(num1, num2);
var larger = Math.max(num1, num2);
console.log(smaller + " is smaller than " + larger);
};
showSmaller(12, 30); // 12
showSmaller(1.2, 0.12); // 0.12
showSmaller(0, -4); // -4
showSmaller(-10, -13); // -13
Listing 7.05 - Using Math.min and Math.max - Task 2
- Write a showLarger function.
var showLarger = function (num1, num2) {
var smaller = Math.min(num1, num2);
var larger = Math.max(num1, num2);
console.log(larger + " is larger than " + smaller);
};
showLarger(12, 30); // 30
showLarger(1.2, 0.12); // 1.2
showLarger(0, -4); // 0
showLarger(-10, -13); // -10
Listing 7.05 - Using Math.min and Math.max - Task 3
- Write a showSmallest function that takes three arguments and displays the smallest of the three.
var showSmallest = function (num1, num2, num3) {
var smallest = Math.min(num1, Math.min(num2, num3));
var message = smallest + " is the smallest of ";
message += num1 + ", " + num2 + " and " + num3;
console.log(message);
};
showSmallest(12, 3, 15); // 3
showSmallest(-1.2, 0.12, 12); // -1.2