Introduction to Lodash

November 20, 2015

Originally forked from Underscore in 2012, Lodash has become the most depended upon NPM package.

Screen Shot 2015-11-19 at 4.42.04 PM

So, what is Lodash exactly?

Lodash brands itself as:

A JavaScript utility library delivering consistency, modularity, performance, & extras.

But, what does this really mean?

Lodash, simplified

At its core, Lodash is just a JavaScript library that provides a bunch of helper functions that make writing JavaScript applications easier.

By that, I mean You include the lodash.js script in your project and then you get access to a ton of great helper functions like:

  • _.findLast
  • _.curry
  • _.findKey
  • _.sum
  • _.capitalize
  • and so many more

All of these helper methods have full browser support back to IE6 and are super fast!

Lodash, an example

Let’s say we have a very basic website. Create an index.html file and paste in:

<!DOCTYPE html>
<html>
    <head>
        <title>A simple website</title>
    </head>
    <body>
        <h1>Hello world!</h1>
    </body>
</html>

Then, download Lodash from their website and source it in your index.html as well as a blank file we’ll call script.js. You should now have something that looks like:

<!DOCTYPE html>
<html>
    <head>
        <title>A simple website</title>
    </head>
    <body>
        <h1>Hello world!</h1>
        <script src=“lodash.js”></script>
        <script src=“script.js”></script>
    </body>
</html>

Now, in our script.js file we have access to all the great functionality namespaced to the “_” object. Here are some cool examples.

// inside script.js

// Capitalize var name = “hello, world”;

var newName = _.capitalize(name); // “HELLO, WORLD”

// Flatten Deep

var nestedArray = [1, 2, [3, 4, [5, 6], 7]];

var flattenedArray = _.flatten(nestedArray, true); // [1, 2, 3, 4, 5, 6, 7]

// First

var list = [6, 5, 4, 3, 2, 1];

var firstInList = _.first(list);

There are a ton of great methods you can find on the website. Let me know in the comments if there’s anything I missed!