What the spread operator does is go through an iterable thing (in this case an array, but it works for strings, Maps and Sets as well), and yields those values one by one. So it’s taking that array (something like [10, 0]
), and when it gets put into Math.min
, which takes a series of arguments, it does something sorta like:
// spreading this array [10, 0]
Math.min(...[10, 0])
// yields the first value, not done yet
Math.min(10, ...[0])
// yields the second value, not done yet
Math.min(10, 0)
// all done!, can now execute Math.min
0
You can see what it’s doing under the hood in the console if you do something like this (the setup may look a bit alien):
// using this array, but change the values in the array to play around, and try with a string
const myIterable = [1, 2, 3, 4, 5]
// this is the step that will look wierd:
const myIterableIterator = myIterable[Symbol.iterator]()
// now I can yield values:
myIterableIterator.next()
// returns { value: 1, done: false }
myIterableIterator.next()
// returns { value: 2, done: false }
myIterableIterator.next()
// returns { value: 3, done: false }
myIterableIterator.next()
// returns { value: 4, done: false }
myIterableIterator.next()
// returns { value: 5, done: false }
myIterableIterator.next()
// returns { value: undefined, done: true }
// we finished
Is sort() a necessity in a problem like this? Or, does it just make solving a problem of this particular type easier? And does it REALLY make it easier or is that just a faulty perception?
It is not necessary, as you can use min and max. It can make it easier, for example, if you want brevity:
const [min, max] = arr.sort((a, b) => a - b);
I still, after years of doing JS, cannot just automatically read arr.sort((a, b) => a - b)
as “sort this array in ascending order”, I still have to pause and parse what it’s doing, so personally I would always prefer Math.min
and Math.max
as it’s obvious what they are doing. Personally I generally avoid using sort unless necessary, mainly out of habit and the [sometimes faulty assumption] that there are better, faster ways to deal with data. There’s nothing wrong with it here though, and if it’s clearer for you and you want to use it, go for it (but as stated, just use sort or min/max, not both), it’s personal preference for me.