Just saw someone write this:
let id = 1;
...
let employee = null;
for (const e of employees) {
if (e.id === id) {
employee = e;
break;
}
}
seems like an overcomplicated way of writing this:
let id = 1;
...
let employee = employees.find(e => e.id === id);
Is there any benefit to using a loop with a break vs a find()?
What is find()'s implementation behind the curtain?
.find() is faster than for...break.
Check this link for test results. for...break is 30% slower than .find()
.find() source code can be found here
.find() is not supported in older browsers like IE11 and below. You need to use a polyfill instead.
.find() is better due to complexity level and the internal algorithm used. Using for...break you will always doing a linear search which means n * n repetitions. The bigger the array, the slower the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With