Use the following function to find the maximum value of an array of numbers in JavaScript.
function findMaximum(array) {
let max = array[0];
for (let i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
Alternatively, you can also use the unpack operator to unpack the array and use the Math.max() function to return the maximum value.
function findMaximum(array) {
return Math.max(...array);
}
You can run this function like this:
let array = [3,40,20,1,10];
console.log(findMaximum(array)); // Prints "40".
Add new comment