π’ JavaScript Math.max() and Math.min() β Explained Simply
In JavaScript, the Math object offers many helpful functions, and among them are Math.max() and Math.min(). These are commonly used to find the largest and smallest values in a group of numbers.
Whether you're building a calculator, handling form validations, or analyzing scores, these functions can be super helpful.
What is Math.max()?
The Math.max() function returns the largest number from a list of numbers.
β Syntax:
Math.max(value1, value2, ..., valueN)
β Example
It returns the largest number from a list of numbers.
console.log(Math.max(5, 12, 3, 9)); // Output: 12
β Example
If we want to find largest value in an array then we can use spread operator.
const numbers = [4, 8, 15, 2];
console.log(Math.max(...numbers)); //15
If we are not passing any value to the Math.max() checks among the zero argument and and it starts checking from the lowest possible value which is -infinity ,as we have not passed any value to the function so it will return the value as -infinity as there is no value except the -infinity.
console.log(Math.max()); //-infinity
What is Math.min()?
The Math.min() function returns the smallest number from a list of numbers.
β Syntax:
Math.min(value1, value2, ..., valueN)
β Example
It returns the largest number from a list of numbers.
console.log(Math.min(5, 12, 3, 9)); // Output: 3
If we want to find largest value in an array then we can use spread operator.
const numbers = [4, 8, 15, 2];
console.log(Math.min(...numbers)); //2
If we are not passing any value to the Math.min() checks among the zero argument and and it starts checking from the highest possible value which is infinity ,as we have not passed any value to the function so it will return the value as infinity because there is no value which javascript can compare .
console.log(Math.min()); //infinity
βοΈ About the Author
Hi, I'm Rutupurna β an MCA student and self-taught developer exploring full-stack development with the MERN stack. I write to share what I learn, build, and debug along the way. Let's grow together! π
Follow me on Dev.to (https://dev.to/rutupurna_panda_2003) or connect on LinkedIn(www.linkedin.com/in/rutupurna-panda) π¬
Top comments (1)
π£οΈ What do you think?
Have you used
Math.max()orMath.min()before?Tell me how you use them or if this helped you! I'm always open to learning more from others. π