Lodash, Lodash, Lodash . . . where do I even start! šŸ¤” There was a time when the JavaScript ecosystem was nascent; it could be compared to the wild west or a jungle if you will, where a lot was going on, but there were very few answers for everyday developer frustrations and productivity. Then Lodash entered the scene, and it felt like a flood that submerged everything. Right from simple everyday needs like sorting to complex data structure transformations, Lodash came loaded (overloaded, even!) with functionality that turned JS devsā€™ life into sheer bliss. And where is Lodash today? Well, it still has all the goodies it offered initially, and then some, but it seems to have lost mind share in the JavaScript community. Why? I can think of a few reasons:

Some functions in the Lodash library were (and still are) slow when applied to large lists. While this wouldā€™ve never affected 95% of the projects out there, influential devs from the remaining 5% gave Lodash a bad press and the effect cascaded down into the grassroots. Thereā€™s a trend in the JS ecosystem (might even say the same thing about the Golang folks) where hubris is more common than necessary. So, relying on something like Lodash is seen as stupid and gets shot down on forums like StackOverflow when people suggest such solutions (ā€œWhat?! Use an entire library for something like this? I can combine filter() with reduce() to achieve the same thing in a simple function!ā€). Lodash is old. At least by JS standards. It came out in 2012, so as of writing, itā€™s been almost ten years. The API has been stable, and not much exciting stuff can be added every year (simply because thereā€™s no need to), which generates boredom for the average overexcited JS developer.

In my opinion, not using Lodash is a significant loss for our JavaScript codebases. It has proven bug-free and elegant solutions for everyday problems we run into at work, and using it will only make our code more readable and maintainable. With that said, letā€™s dive into some of the common (or not!) Lodash functions and see just how incredibly helpful and beautiful this library is.

Clone . . . deeply!

Since objects are passed by reference in JavaScript, it creates a headache for developers when wanting to clone something with the hope that the new data set is different. Notice how in our pure innocence and despite our good intentions, the original people array mutated in the process (Arnoldā€™s specialization changed from C++ to JS) ā€” a major blow to the integrity of the underlying software system! Indeed, we need a way to make a true (deep) copy of the original array. You can perhaps argue that this is a ā€œsillyā€ way of coding in JS; however, the reality is a bit complicated. Yes, we have the lovely destructuring operator available, but anyone who has tried to destructure complex objects and arrays knows the pain. Then, thereā€™s the idea of using serialization and de-serialization (perhaps JSON) to achieve deep copying, but it only makes your code messier for the reader. By contrast, look how amazingly elegant and concise is the solution when Lodash gets used: Notice how the people array is untouched after deep cloning (Arnold still specializes in C++ in this case). But more importantly, the code is straightforward to understand.

Remove duplicates from an array

Removing duplicates from an array sounds like an excellent interview/whiteboarding problem (remember, when in doubt, throw a hashmap at the problem!). And, of course, you can always write a custom function to do that, but what if you encounter several different scenarios in which to make your arrays unique? You could write several other functions for that (and risk running into subtle bugs), or you could just use Lodash!

Our first example of unique arrays is rather trivial, but it still represents the speed and reliability that Lodash brings to the table. Imagine doing this by writing all the custom logic yourself! Notice that the final array is not sorted, which of course, isnā€™t of any concern here. But now, letā€™s imagine a more complicated scenario: we have an array of users we pulled from somewhere, but we want to make sure it contains only unique users. Easy with Lodash! In this example, we used the uniqBy() method to tell Lodash that we want the objects to be unique on the id property. In one line, we expressed what couldā€™ve taken 10-20 lines and introduced more scope for bugs! Thereā€™s a lot more stuff available around making things unique in Lodash, and I encourage you to have a look at the docs.

Difference of two arrays

Union, difference, etc., might sound like terms best left behind in dull high school lectures on Set Theory, but they pop up more often than not in everyday practice. Itā€™s common to have a list and want to merge another list with it or wanting to find which elements are unique to it as compared to another list; for these scenarios, the difference function is perfect. Letā€™s begin the journey of difference by taking a simple scenario: youā€™ve received a list of all the user ids in the system, as well as a list of those whose accounts are active. How do you find the inactive ids? Simple, right? And what if, as it happens in a more realistic setting, you have to work with an array of objects instead of plain primitives? Well, Lodash has a nice differenceBy() method for this! Neat, right?! Like difference, there are other methods in Lodash for common set operations: union, intersection, etc.

Flattening arrays

The need to flatten arrays arises quite often. One use case is that youā€™ve received an API response and need to apply some map() and filter()combo on a complex list of nested objects/arrays to pluck out, say, user ids, and now youā€™re left with arrays of arrays. Hereā€™s a code snippet depicting this situation: Can you guess what postPaidUserIds now looks like? Hint: itā€™s disgusting! Now, if youā€™re a sensible person, you donā€™t want to write custom logic to extract the order objects and lay them out nicely in a row inside an array. Just use the flatten() method and enjoy the grapes: Do note that flatten() only goes one level deep. That is if your objects are stuck two, three, or more levels deep, flatten() they will disappoint you. In those cases, Lodash has the flattenDeep() method, but do be warned that applying this method on very large structures can slow things down (as behind the scenes, thereā€™s a recursive operation at work).

Is the object/array empty?

Thanks to how ā€œfalsyā€ values and types work in JavaScript, sometimes something as simple as checking for emptiness results in existential dread.

How do you check if an array is empty? You can check whether its length is 0 or not. Now, how do you check if an object is empty? Wellā€¦wait a minute! This is where that uneasy feeling sets in, and those JavaScript examples containing stuff like [] == false and {} == false start circling our heads. When under pressure to deliver a feature, landmines like these are the last thing you need ā€” they will make your code hard to understand, and they will introduce uncertainty in your test suite.

Working with missing data

In the real world, data listen to us; no matter how badly we want it, itā€™s rarely streamlined and sane. One typical example is missing null objects/arrays in a large data structure received as API response.

Suppose we received the following object as an API response: As shown, we generally get an order Object in the response from the API, but itā€™s not always the case. So, what if we have some code that relies on this object? One way would be to code defensively, but depending on how nested the order object is, weā€™d soon be writing very ugly code if we wish to avoid runtime errors: šŸ¤¢šŸ¤¢ Yup, very ugly to write, very ugly to read, very ugly to maintain, and so on. Thankfully, Lodash has a straightforward way of dealing with such situations. Thereā€™s also the fantastic option of providing a default value instead of getting undefined for missing stuff: I donā€™t know about you, but get() is one of those things that bring tears of happiness to my eyes. Itā€™s not anything flashy. Thereā€™s no consulted syntax or options to memorize, yet look at the amount of collective suffering it can alleviate! šŸ˜‡

Debouncing

In case youā€™re unfamiliar, debouncing is a common theme in frontend development. The idea is that sometimes itā€™s beneficial to launch an action not immediately but after some time (generally, a few milliseconds). What does that mean? Hereā€™s an example.

Imagine an e-commerce website with a search bar (well, any website/web app these days!). For better UX, we donā€™t want the user to have to hit enter (or worse, press the ā€œsearchā€ button) to show suggestions/previews based on their search term. But the obvious answer is a bit loaded: if we add an event listener to onChange() for the search bar and fire off an API call for every keystroke, weā€™d have created a nightmare for our backend; there would be too many unnecessary calls (for example, if ā€œwhite carpet brushā€ is searched, there will be a total of 18 requests!) and almost all of these will be irrelevant because the user input hasnā€™t finished. The answer lies in debouncing, and the idea is this: do not send an API call as soon as the text changes. Wait for some time (say, 200 milliseconds) and if by that time thereā€™s another keystroke, cancel the earlier time count and again start waiting. As a result, itā€™s only when the user pauses (either because theyā€™re thinking or because theyā€™re done and they expect some response) that we send an API request to the backend. The overall strategy I described is complicated, and I wonā€™t dive into the synchronization of timer management and cancellation; however, the actual debouncing process is very simple if youā€™re using Lodash. If youā€™re thinking setTimeout() I wouldā€™ve done the same job, well, thereā€™s more! Lodashā€™s debounce comes with many powerful features; for example, you might want to ensure that the debounce isnā€™t indefinite. That is, even if thereā€™s a keystroke every time the function is about to fire off (thus canceling the overall process), you might want to make sure that the API call is made anyway after, say, two seconds. For this, Lodash debounce() has the maxWait option: Do check out the official docs for a deeper dive. Theyā€™re full of super-important stuff!

Remove values from an array

I donā€™t know about you, but I hate to write code for removing items from an array. First, I have to get the itemā€™s index, check whether the index is actually valid and if so, call the splice() method, and so on. I can never remember the syntax and thus needs to look things up all the time, and at the end of it, I am left with the nagging feeling that Iā€™ve let some stupid bug creep in.

Please note two things: Thereā€™s another related method called pullAll() that accepts an array as the second parameter, making it easier to remove multiple items at once. Granted that we could just use pull() with a spread operator, but remember that Lodash came at a time when the spread operator wasnā€™t even a proposal in the language!

Last index of an element

JavsScriptā€™s native indexOf() method is cool, except when youā€™re interested in scanning the array from the opposite direction! And yet again, yes, you could just write a decrementing loop and find the element, but why not use a lot more elegant technique?

Hereā€™s a quick Lodash solution using the lastIndexOf() method: Unfortunately, thereā€™s no variant of this method where we can look up complex objects or even pass a custom lookup function.

Zip. Unzip!

Unless youā€™ve worked in Python, zip/unzip is a utility you may never notice or imagine in your entire career as a JavaScript developer. And perhaps for a good reason: thereā€™s rarely the kind of desperate need for zip/unzip as there is for filter(), etc. However, itā€™s one of the best lesser-known utilities around and can help you create succinct code in some situations. Contrary to what it sounds like, zip/unzip has nothing to do with compression. Instead, itā€™s a grouping operation where arrays of the same length can be converted into a single array of arrays with elements at the same position packed together (zip()) and back (unzip()). Yeah, I know, itā€™s getting hazy trying to make do with words, so letā€™s look at some code: The original three arrays got converted into a single one with two arrays only. And each of these new arrays represents a single animal with all its into in one place. So, the index 0 tells us that type of animal it is, the index 1 tells us its size, and the index 2 tells us its weight. As a result, the data is now easier to work with. Once youā€™ve applied whatever operations you need to on the data, you can break it up again using unzip() and send it back to the original source: The zip/unzip utility isnā€™t something that will change your life overnight, but it will change your life one day!

Conclusion šŸ‘Øā€šŸ«

(I put all the source code used in this article here for you to try directly from the browser!) The Lodash docs are chock-full of examples and functions that will just blow your mind. In a day and age where masochism seems to be increasing in the JS ecosystem, Lodash is like a breath of fresh air, and I highly recommend that you use this library in your projects!

10 Important Lodash Functions for JavaScript Developers - 3510 Important Lodash Functions for JavaScript Developers - 2710 Important Lodash Functions for JavaScript Developers - 1010 Important Lodash Functions for JavaScript Developers - 9210 Important Lodash Functions for JavaScript Developers - 9510 Important Lodash Functions for JavaScript Developers - 4210 Important Lodash Functions for JavaScript Developers - 6010 Important Lodash Functions for JavaScript Developers - 7210 Important Lodash Functions for JavaScript Developers - 1010 Important Lodash Functions for JavaScript Developers - 7610 Important Lodash Functions for JavaScript Developers - 8410 Important Lodash Functions for JavaScript Developers - 8710 Important Lodash Functions for JavaScript Developers - 3810 Important Lodash Functions for JavaScript Developers - 9210 Important Lodash Functions for JavaScript Developers - 8110 Important Lodash Functions for JavaScript Developers - 7110 Important Lodash Functions for JavaScript Developers - 2610 Important Lodash Functions for JavaScript Developers - 1510 Important Lodash Functions for JavaScript Developers - 210 Important Lodash Functions for JavaScript Developers - 2510 Important Lodash Functions for JavaScript Developers - 3710 Important Lodash Functions for JavaScript Developers - 110 Important Lodash Functions for JavaScript Developers - 8610 Important Lodash Functions for JavaScript Developers - 5910 Important Lodash Functions for JavaScript Developers - 4610 Important Lodash Functions for JavaScript Developers - 7810 Important Lodash Functions for JavaScript Developers - 2810 Important Lodash Functions for JavaScript Developers - 1110 Important Lodash Functions for JavaScript Developers - 8910 Important Lodash Functions for JavaScript Developers - 9010 Important Lodash Functions for JavaScript Developers - 9710 Important Lodash Functions for JavaScript Developers - 110 Important Lodash Functions for JavaScript Developers - 66