Get the Min/Max Values in a Set in JavaScript

Borislav Hadzhiev

Last updated: Nov 6, 2021

Photo from Unsplash

**To get the min and max values in a Set, use the spread syntax (...) to pass
the Set to the Math.min() and Math.max() methods. The Math.min and
Math.max methods return the lowest and highest of the passed in numbers.**

index.js

`const set1 = new Set([3, 5, 8]); const min = Math.min(...set1); console.log(min); // 👉️ 3 const max = Math.max(...set1); console.log(max); // 👉️ 8`

A Set is an iterator object, just like an array.

We can't pass the iterator object directly to the Math.max and Math.min methods because they expect multiple, comma-separated numbers and not an iterator.

index.js

`const min = Math.min(1, 3, 5); console.log(min); // 👉️ 1 const max = Math.max(1, 3, 5); console.log(max); // 👉️ 5`

To unpack the values from the `Set`

in the calls to the `Math.min()`

and
`Math.max()`

methods, we used the
spread syntax (...).

You can imagine that the spread syntax passes the values from the `Set`

and
passes them as comma-separated parameters to the methods.