Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop with break vs find() in JavaScript

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?

like image 984
Artur Grigio Avatar asked Jun 13 '18 18:06

Artur Grigio


1 Answers

Perfomance

.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.


Opinion

.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.

like image 55
Luis felipe De jesus Munoz Avatar answered Sep 21 '22 12:09

Luis felipe De jesus Munoz