Coding: Finding the Min/Max Values in an Array using JavaScript
In this post, we will be discussing a simple JavaScript function that can be used to find the minimum and maximum values in an array. The function, called “findMinMax,” takes in an array as its only parameter.

The function starts by initializing two variables, “min” and “max,” to the first element of the array. It then uses a for loop to iterate through the rest of the array, comparing each element to the current min and max values. If an element is greater than the current max, it becomes the new max. If an element is less than the current min, it becomes the new min.
Here’s the full code for the function:
function findMinMax(arr) {
let min = arr[0];
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
return { min: min, max: max };
}Here’s an example of how you can use the function:
let numbers = [3, 5, 1, 10, 2];
let minMax = findMinMax(numbers);
console.log(minMax); // Output: { min: 1, max: 10 }In the example above, we have an array of numbers called “numbers.” We pass this array as an argument to the “findMinMax” function, and assign the returned object to a variable called “minMax.” We then log the “minMax” variable to the console, which outputs the minimum and maximum values in the array: 1 and 10, respectively.
It’s a simple function with O(n) time complexity and easy to understand. This function can be useful in situations where you need to find the range of values in an array, and is a good example of how a small, specific function can be useful in many different programs.
If you’re interested in learning more about coding in Javascript, be sure to follow me for more code snippets and examples. I’ll be sharing valuable information and tips on how to master the language and improve your skills as a developer. So, stay tuned for more updates, and let’s continue learning together.
Happy learning 😄
Do support our publication by following it





