DEV Community

loading...

Discussion on: Top 20 JavaScript tips and tricks to increase your Speed and Efficiency

Collapse
martinmuzatko profile image
Martin Muzatko

min: Math.min(...numbers)
max: Math.max(...numbers)

Collapse
techygeeky profile image
Kapil Raghuwanshi🖥 Author • Edited

Thanks for reminding this tip @martinmuzatko .

const array = [4,5,7,2,3];
Math.min(...array)
// Output: 2
Math.max(...array)
// Output: 7
Enter fullscreen mode Exit fullscreen mode
Collapse
boydevelopr profile image
FredDev

Please what tool is used to make this code snippet embedment on the pages?

Thread Thread
techygeeky profile image
Kapil Raghuwanshi🖥 Author

These are just code test only. Use 3 backticks before and after your code. Check the preview.

Collapse
tomy profile image
Tomy Smith

Exactly, not sure of the advantage of using reduce over these common functions.

Collapse
andrewbridge profile image
Andrew Bridge

I'd go further and agree with this thread and follow up video that advise against using reduce in nearly every situation. It's often used when a simpler or more readable alternative is available, and leads to harder to read, harder to maintain code. As proven with this example above.

Collapse
liquorburn profile image
liquorburn • Edited

I've made a simple benchmark, it seems that reduce() is faster than Math.max()

dev-to-uploads.s3.amazonaws.com/up...

Thread Thread
techygeeky profile image
Kapil Raghuwanshi🖥 Author

That's awesome @liquorburn . I have added the fastest one only.

Thread Thread
tomy profile image
Tomy Smith • Edited

It's actually the spread operator that's taking the time there. Though admittedly, there aren't many cases you'd have a hardcoded list of values to find the max of, it's worth pointing out.

dev-to-uploads.s3.amazonaws.com/up...

Collapse
techygeeky profile image
Kapil Raghuwanshi🖥 Author

Well, of course above methods seems simpler for finding min/max but one should not underestimate the power of reduce in JavaScript. There are several technique where you can solve problems mostly in one reduce statements only.

Thread Thread
erasmuswill profile image
Wilhelm Erasmus

But in this case a helper method that does the full job exists so why bother with reduce for this use case? I admittedly do not use it enough but just saying