How to use the forEach Method In Javascript
The forEach method iterates over each element in the array, comparing each element to a variable (`max`) initialized to the first element. If the current element is greater than max, max is updated. After the loop, max holds the largest value.
Example: In this example The function findLargestWithForEach iterates through each element of the array using forEach and updates the max variable if it finds a number greater than the current maximum.
function findLargestWithForEach(arr) {
let max = arr[0];
arr.forEach(num => {
if (num > max) {
max = num;
}
});
return max;
}
console.log(findLargestWithForEach([1, 2, 3, 4, 5]));
Output
5
Javascript Program to Find the Largest Element in an Array
Finding the largest element in an array is a common task in JavaScript, useful in various scenarios such as data analysis, sorting, and mathematical computations. This article explores several methods to efficiently determine the largest element, ensuring robust and optimized solutions for your coding needs. Let’s first see simple examples input and output.
Examples:
Input: arr = [10, 20, 4]
Output: 20
Explanation: Among 10, 20 and 4, 20 is the largest.Input : arr = [20, 10, 20, 4, 100]
Output : 100
Contact Us