find the largest element in an array in javascript

To find the largest element in an array in JavaScript, we can use the Math.max() method. One way to use Math.max() is to apply it directly to an array using the spread operator (...), like so:

index.tsx
const arr = [3, 1, 7, 4, 2, 9, 5];
const largest = Math.max(...arr);
console.log(largest); // Output: 9
104 chars
4 lines

In this example, Math.max(...arr) takes all the elements in the array arr and returns the largest one. This value is then assigned to the variable largest.

It's important to note that calling Math.max() directly on an array will not work, since the method expects a list of arguments, not an array. That's why the spread operator is necessary to "spread" the array elements into separate arguments.

Alternatively, we could also use a for loop to iterate through the array and compare each element to a variable holding the current maximum value. Here's an example:

index.tsx
const arr = [3, 1, 7, 4, 2, 9, 5];
let largest = arr[0];
for (let i = 1; i < arr.length; i++) {
  if (arr[i] > largest) {
    largest = arr[i];
  }
}
console.log(largest); // Output: 9
185 chars
9 lines

In this example, we initialize largest to the first element of the array, and then loop through the rest of the array, comparing each element to largest. If an element is greater than largest, we update the value of largest accordingly. Finally, we log the value of largest to the console.

gistlibby LogSnag