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.tsx104 chars4 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.tsx185 chars9 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