find the smallest element in an array in javascript

To find the smallest element in an array in JavaScript, you can use the Math.min function combined with the spread operator (...) to pass the array elements as arguments. Here's the code:

index.tsx
const myArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];

const smallest = Math.min(...myArray);

console.log(smallest); // outputs: 1
129 chars
6 lines

In this code, we define an array (myArray) with some arbitrary values. We then call the Math.min function with the spread operator to pass each element of myArray as an argument. The returned value is assigned to the smallest variable.

Finally, we log the smallest variable to the console, resulting in the smallest element of the array being outputted: 1.

gistlibby LogSnag