Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to find min/max values without Math functions in JavaScript ?

  • Last Updated : 09 Nov, 2021

In this article, we will learn how to find the minimum and maximum values in an array without using Math functions. We know that Math.max() returns the maximum number passed in an array whereas Math.min() returns the minimum number passed.

Approach: The same functionality of the Math functions can be implemented using a loop that will iterate the numbers present in the array to find maximum and minimum values inside the array.

We will keep checking all the elements in the array using a loop. If we find any element greater than the previous “max” value, we set that value as the max value. Similarly, we keep on checking for any element lesser than the “min” value. If we get any such element, we replace the value of “min” with a smaller value. Thus, using the loop function, we can get the maximum and minimum values entered in an array/list.

The below example will demonstrate the above approach.



    // Array of numbers where the maximum
    // and minimum are to be found
    const array = [-1, 2, -5, 8, 16];
    // Setting a number of the given array as
    // value of max and min we choose 0th index
    // element as atleast one element should be
    // present in the given array
    let max = array[0], min = array[0];
    for (let i = 0; i < array.length; i++) {
        // If we get any element in array greater
        // than max, max takes value of that
        // larger number
        if (array[i] > max) { max = array[i]; }
        // If we get any element in array smaller
        // than min, min takes value of that
        // smaller number
        if (array[i] < min) { min = array[i]; }
    console.log("max = " + max);
    console.log("min = " + min);

Output: The maximum and the minimum number of the array is found using the approach.

max = 16
min = -5
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!