How to use a ForEach Loop In Javascript
Using a forEach loop iterates through the array, updating the largest element encountered. It initializes the largest element with the first element, then compares each subsequent element, updating the largest value accordingly.
Example
const array = [10, 5, 20, 8, 15];
let largest = array[0];
array.forEach(element => {
if (element > largest) {
largest = element;
}
});
console.log("Largest element:", largest);
Output
Largest element: 20
JavaScript Program to Find Largest Element in an Array
In this article, we are going to learn about the largest element in an array in JavaScript. The largest element in an array refers to the value that holds the greatest numerical or lexicographic (string) order among all elements present in the array.
Example:
Input : [10, 15, 38, 20, 13];
Output: 38
Here we will see the 38 is the largest elements in the given array.
Several methods can be used to find the largest Element in an Array in Javascript, which are listed below:
Table of Content
- Using the reduce() Method
- Using the Spread Operator and Math.max() Method
- Using for Loop
- Using the sort() method
- Using a ForEach Loop