Lodash — get or result?

Apurva Jain
2 min readJul 24, 2018

--

There are many ways available to do the same task, all we are looking for is — How to do it the right way?

Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc. It provides many functional utilities that can keep your yard green and clean. There are sometimes multiple options available to do the same thing — _.get and _.result functions at core gets the value at path of object.

Do we really understand the difference between the two? Let’s explore them in detail! 👀

get( object, path, [defaultValue] )

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

Here in the above example, on trying to read the property y of my_object using _.get function returns the function yo.

result( object, path, [defaultValue] )

This method is like _.get except that if the resolved value is a function it’s invoked with the this binding of its parent object and its result is returned.

Here in the above example, on trying to read the property y of my_object using _.result function returns the result of executing the yo function.

Which & Why?

As we all know, the more dependencies we have in a function, the slower it will run. And even such a lightweight library can affect the speed of function, especially when it comes to complex functions with iterations and recursion. It’s really important to choose the right lodash function.

Lets compare the performance of _.get and _.result 🔥

The library used for doing the performance comparison is bench.js. We run a very simple piece of code to test the performance of the core functionality of _.get and _.result .

And the results are as follows:

For this simple test with few iteration, _.get can perform ~3538 processes/ms on an average, whereas _.result can only perform ~2505 Hence proving that the function _.get is slimmer and ~30% faster than _.result.💃

So, depending on your use case, choose your lodash function wisely. 😎

Happy Coding !!!

Follow me on Medium or Twitter to read more about JavaScript and libraries!

--

--

Apurva Jain
Apurva Jain

Written by Apurva Jain

Full stack developer with expertise in JavaScript and React. On my radar: #travel #technology #sports #health

No responses yet