In JavaScript, we can use:
Math.min()
to find the minimum of n elements.Math.max()
to find the maximum of n elements.Math.min(...numbers);
Math.max(...numbers);
let a = 10;let b = 20;let min = Math.min(a, b);console.log(`Min of ${a} and ${b} is ${min}`);let max = Math.max(a, b);console.log(`Max of ${a} and ${b} is ${max}`);
We can pass in any number of arguments to both the Math.max()
and Math.min()
methods.
These methods will return NaN
if any of the arguments passed cannot be converted to a number.
console.log("Calling Math.min with multiple arguments -- 10,20,30,-10")let min = Math.min(10,20,30,-10);console.log("Min value is = ", min);console.log("\n----------\n")console.log("Calling Math.max with multiple arguments -- 10,20,30,-10")let max = Math.max(10,20,30,-10);console.log("Max value is = ", max);console.log("\n----------\n")console.log("Calling Math.min with argument which cannot be converted to a number");console.log("Math.min(10, 'a') = ", Math.min(10, "a"));console.log("\n----------\n")console.log("Calling Math.max with argument which cannot be converted to a number");console.log("Math.max(10, 'a') = ", Math.max(10, "a"));
If we don’t pass any argument to the Math.min()
method, it will return Infinity
.
When we pass a single argument to the Math.min()
method, the argument is compared with infinity and the passed value is returned. This is because when we compare any number to infinity, infinity will always be the higher value; so, the number becomes the min value.
console.log("Calling Math.min with no arguments ");let min = Math.min();console.log(min);console.log("\n-----\nCalling Math.min with one arguments ");min = Math.min(1);console.log(min);
If we don’t pass in any argument to the Math.max()
method, it will return -Infinity
.
If we pass a single argument to the Math.max()
method, the argument is compared with -infinity
and the passed value is returned. The reason for this is that when we compare any number to -infinity
, -infinity
will always be the lowest value; so, the number becomes the max value.
console.log("Calling Math.max with no arguments ");let max = Math.max();console.log(max);console.log("\n-----\nCalling Math.max with one arguments ");max = Math.max(1);console.log(max);
We can use the spread operator on an array to find the minimum and maximum value of an array.
let arr = [1,2,3,4,5];console.log("Min value of the array is", Math.min(...arr));console.log("Max value of the array is", Math.max(...arr));