How to find the largest number in an array in javascript

When it comes to finding the largest element in an array, one way that usually comes to mind is to sort the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and so on, and the last element will be the largest element of the array.

With this solution, the code will take longer to execute and we will say that our code is not optimized.

The most optimized method is to use a max() method from the static object Math which is a built-in object in javascript that has properties and methods for mathematical constants and functions.

For example:

  const arr = [1, 5, 16, 9, -98, 23, -12, 892, 2, -23];

  console.log(Math.max(...arr));
  //output: 892