DEV Community

Rutupurna panda
Rutupurna panda

Posted on

Understanding Math.max() and Math.min() in Javascript

πŸ”’ 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)
Enter fullscreen mode Exit fullscreen mode

βœ… Example

It returns the largest number from a list of numbers.

console.log(Math.max(5, 12, 3, 9)); // Output: 12
Enter fullscreen mode Exit fullscreen mode

βœ… 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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

What is Math.min()?

The Math.min() function returns the smallest number from a list of numbers.

βœ… Syntax:

Math.min(value1, value2, ..., valueN)
Enter fullscreen mode Exit fullscreen mode

βœ… Example

It returns the largest number from a list of numbers.

console.log(Math.min(5, 12, 3, 9)); // Output: 3
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

✍️ 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)

Collapse
 
rutupurna_panda_2003 profile image
Rutupurna panda

πŸ—£οΈ What do you think?

Have you used Math.max() or Math.min() before?

Tell me how you use them or if this helped you! I'm always open to learning more from others. πŸš€