How to find maximum element in an array in Javascript

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.

  1. 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, max is 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;

}

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x