Coder007
Coder007

Reputation: 37

What is the difference between find function in Underscore(JavaScript Lib ) and normal java-script function?

i am using underscore function in my JavaScript Code but after deploying my site in production. I realized, normal JavaScript function take less time than underscore library`s function

What is the main difference between two of them if they are using same source(JavaScript)

1.Underscore library function

var value= _.find(array, function(elementInArray) {
            return elementInArray === ListOfArray;
        });

2.Normal JavaScript function

var value= array.find(function(elementInArray) {
            return elementInArray === ListOfArray;
        });

Upvotes: 1

Views: 572

Answers (2)

Borja Tur
Borja Tur

Reputation: 817

In addition to @fjc answer there is also another big difference between those two functions:

Native Array.find only can be used with Arrays returning a TypeError when you try to call it for instance:

con myString = 'a';
myString.find(e => e === 'a');

Whereas you can use underscore find with this same example and it will return undefined instead of throwing an error. So as first consequence you would have to be more cautious using native Array.find and adding the proper guards in your code checking that you use it calling with an Array especially with variables that are going to be dynamically instantiated

Upvotes: 0

fjc
fjc

Reputation: 5815

Underscore was written with wide browser compatibility in mind. At the time they wrote the _.find() method, Array.find() was by far not available in all browsers. It is, for example, not available in most IE versions.

Hence, there's some overhead involved in building a method that's running in all major browsers, compared to directly implementing Array.find in a way that's optimized for each browser's JS engine.

Upvotes: 4

Related Questions