Open In App

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

Example 1: The below example will demonstrate the above approach.

JavaScript




// 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

Example 2: In this example, we will get max and min without function.

Javascript




const arr = [-7,-10,8,6,5,4];
 
let max = arr[0]
let min = arr[0];
for (let i = 0; i < arr.length; i++) {
    // If the element is greater
    // than the max value, replace max
    if (arr[i] > max) { max = arr[i]; }
 
    // If the element is lesser
    // than the min value, replace min
    if (arr[i] < min) { min = arr[i]; }
}
console.log("Max element is: " + max);
console.log("Min element is:"+min);


Output:

Max element is: 8
Min element is:-10


Last Updated : 28 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads