Stop using loops, just lodash everything!

Pranav Jindal
6 min readMay 15, 2018

--

What? 🤨

Loops are the most fundamental programming concepts that anyone-into-coding learns and I’m asking you to not use them?

Well, yes and no..!!

Loopers 😏 like for or while will always be part of any programming language and nothing will ever replace them, but using them as your mainstream constructs to do daily things is ugly and cumbersome.

Whenever we have to work on collections, be it arrays or objects, we just use a bunch of loops and conditions to get the work done but while doing that, all the code just gets littered with few useless extra variables that you never intended to make.

Let’s take a simple example:

You have an unsorted array employees where each employee has their name and salary (as string) and you need to extract top 10 salaries.

Let’s take this up normally:

let employees = [{name: 'Gilfoyle', salary: "90"}, {name: 'Dinesh', salary: "72"}, and so on........]let salaries = []for (let i = 0; i< employees.length; i++){
salaries.push(employees[i].salary)
}
salaries = salaries.sort((a,b)=> parseInt(b)- parseInt(a))
let top10 = salaries.slice(0,9)

That was a very simple operation but still took some lines of code.

Lodash: Move aside everyone, I’ll make it one-liner!

let employees = [{name: 'Gilfoyle', salary: "90"}, {name: 'Dinesh', salary: "72"}, and so on........]let top10 = _(employees).map('salary').orderBy(_.parseInt,'desc').take(10).value()

First, please don’t tell me that there is a better way of doing this using loops. There could be, but my point here is, look at those two code blocks again.

To do a simple operation as above, you ended up writing 4–5 lines of code using loops. If someone reads that code, like you just did, their brain would have to parse those lines, and would require some level concentration to understand.

The second one doesn’t even looks like code but just description of what you intend to do. You extracted (mapped) salary of employees, ordered them in descending order, took 10 of the residue and done 😎!

If you already know the new ES5/ES6 array functions, you could argue that why add up a whole library when language already provides them. Well, to an extent those features work but lodash is a library dedicated to reduce the mundane tasks developers keep doing and has a whole lot to provide which is taken up further.

Lodash is like Batman’s utility belt for a JavaScript developer that provides almost everything you need while writing code.

Underscore fans, your library is also very cool, but lodash has surpassed it and has become a super-set of underscore. In fact, lodash is the most depended upon package on npm. Comparing libraries is not the intent of this article, use the one which suits your requirements.

If we break down what we usually do using loops, it would turn out that there are a limited set of operations that we do over collections to solve most problems, and they would be:

  1. Extract/transform (map) values from a collection
  2. Filter values based on some criteria
  3. Group values based on some criteria
  4. Aggregate (reduce) collection to a single value
  5. …and other general operations like sorting, removing, inserting, etc.

Achieving these is very much possible using loops but not pretty and so lodash provides few functions to clean up that mess, but before getting to those functions, let's first clear up few terminologies:

  • predicate: A function that takes a value and returns a boolean based on input.
  • iteratee: A function that takes one or more values as input and returns a value based on that input.
  • comparator: A function that takes two values as input and returns a boolean based on both inputs.

You don’t have to write these functions every time and there are shorthand notations to these which makes lodash very succinct and we will take them as we go.

I’d barely be scratching the surface of what lodash is capable of and covering all that is not possible in a single article. The intent is to make new developers aware that using loops and basic programming constructs everywhere and everyday is not ideal. Using libraries like lodash makes your code concise and a breeze to read making it manageable.

Taking up our initial breakdown of common operations:

  1. map: A function that takes a collection and an iteratee as input and returns an array running the iteratee on each item of collection.

For example:

_.map([4, 8], n => n*n)// [16, 64]let employees = [{name: 'Gilfoyle', salary: "90"}, {name: 'Dinesh', salary: "72"}]_.map(employees, emp => emp.salary)// ["90", "72"]

A shorthand for iteratee in second example can be as simple as a string naming the property to extract.

_.map(employees, 'salary')

2. filter: A function that takes a collection and a predicate as input and returns a filtered array running the predicate on each item of collection for which predicate returned true.

var pipers = [
{ piper: 'Richard Hendricks', genius: true, billionaire: false },
{ piper: 'Bag Head', genius: false, billionaire: false },
{ piper: 'Russ Hanneman', genius: false, billionaire: true }
]
_.filter(pipers, piper => piper.billionaire)
//[{ piper: 'Russ Hanneman', genius: false, billionaire: true }]

Shorthand for predicate in second example can be as simple as a string naming the property or a partial object or a property-value pair.

_.filter(pipers, 'billionaire')
//[{ piper: 'Russ Hanneman', genius: false, billionaire: true }]
_.filter(users, {genius: true, billionaire: false})
//[{ piper: 'Richard Hendricks', genius: true, billionaire: false }]
_.filter(users, ['billionaire', false])
//[{ piper: 'Richard Hendricks', genius: true, billionaire: false },
{ piper: 'Bag Head', genius: false, billionaire: false }]

3. groupBy : A function that creates an object composed of keys generated from the results of running each element of collection thru iteratee.

_.groupBy([6.1, 4.2, 6.3], Math.floor);
{ 4: [4.2], 6: [6.1, 6.3] }

A shorthand for iteratee can again be as simple as a string naming a property.

var pipers = [
{ piper: 'Richard Hendricks', genius: true, billionaire: false },
{ piper: 'Bag Head', genius: false, billionaire: false },
{ piper: 'Russ Hanneman', genius: false, billionaire: true }
]
_.groupBy(pipers, 'genius')
/*
{
true: [
{
"piper": "Richard Hendricks",
"genius": true,
"billionaire": false
}
],
false: [
{
"piper": "Bag Head",
"genius": false,
"billionaire": false
},
{
"piper": "Russ Hanneman",
"genius": false,
"billionaire": true
}
]
}
*/

4. reduce: A function that reduces collection to a value which is the accumulated result of running each element in collection thru iteratee, where each successive invocation is supplied the return value of the previous.

Reduce is better used when you don’t want to make extra variables and just want to extract a value off a collection. It is better explained here.

Lodash has various other general operations like sorting/ordering arrays, removing items from arrays, intersecting arrays, finding difference between arrays and so on, which are very handy in common day to day programming and once you know them (which is just a matter of days), you’ll feel, using loops is so-stone-age.

One of the premier features of Lodash that I used in the first example is chaining ⛓️ which lets you chain your operations without making you save intermediate results in variables and then passing on to next functions. Chaining makes your code very brief, descriptive and compact without any mess.

For example, if you look at the following code, it becomes as easy as reading a statement to guess what type the data would be and what the code actually does:

let statuses = _(data).map('status').uniq().sortBy().value()

data must be a collection of objects, you extracted all status, removed duplicates leaving unique set of status, sorted them and voilà!

There are two ways of chaining in lodash which have been explained very well here.

Also, Lodash auto optimizes your chain of functions to make it as performant as possible using lazy evaluation.

I can keep on defining these awesome functions and features but nothing is better than Lodash’s documentation, so hop-on and dive into the world of no-loops.

Thank you for reading, have a great day!! ✌️

👉Attention beginners! Do not directly jump over to such libraries without mastering loops and basic programming constructs. Whenever you need to solve a new algorithmic problem, it’s best to fallback to loops to make an optimized solution.

--

--

Pranav Jindal

JavaScript | VueJS | NodeJS | Typescript | AngularJS | Code Quality