We can find maximum element of an array in Javascript using Math.max() built in function and also by looping through the array values and check the maximum value.
- Find maximum element with Math.max() method with Spread operator:
Math.max() is a built-in JavaScript function that returns the largest number from a list of values with Spread operator. The spread operator (...) expands the array elements into individual arguments.
Example Code:
const arr = [32,8, 10, 12, 19];
let max = Math.max(…arr);
console.log(“Maximum element is”+max);
2. Find maximum element using for loop:
- This approach initializes the first element as the maximum.
- It iterates through the array and compares each element with the current
max. - If a larger value is found,
maxis updated. - At the end of the loop, the largest number is returned.
✅ When to use:
- Useful in interviews or when working in environments without modern JS features.
- When you want to understand or demonstrate the logic step-by-step.
Example Code:
const secArr = [32,8, 10, 12, 19, 45];
let maxValue = maxElementOfArray(secArr);
console.log(“Maximum element is”+maxValue);
//function to retrieve maximum element
function maxElementOfArray(secArr){
let len = secArr.length;
let max = secArr[0];
for(let i=1;i<len;i++){
if(secArr[i]>max){
max = secArr[i];
}
}
return max;
}