Tuesday, January 28, 2014

Using Lodash With jQuery

Both Lodash and jQuery are very powerful libraries that serve two very distinct purposes. Lodash is a utility library concerned with JavaScript data structures — arrays, abjects, and functions. On the other hand, jQuery is concerned with the DOM, Ajax, and event handling. There is, however, some overlap. For example, both libraries help the developer write less code. They're also complimentary to one another — where Lodash lacks in anything DOM or Ajax related, jQuery soars. Where we need fancy array queries and short-cuts, Lodash picks up the slack.

There's even the possibility for applying Lodash functions to jQuery objects. For example, take a look at this code.

var $p = $( "p" );
    
_.each( $p, function( p ) {
    $( p ).css( "font-weight", "bold" );
});
    
$( _.first( $p ) ).css( "text-decoration", "underline" );
    
$( _.last( $p ) ).css( "text-decoration", "underline" );

This demonstrates that it's indeed possible to apply your typical Lodash collection and array functions to jQuery objects. Here, we're using _.each() to iterate over the jQuery object $p. We're also using _.first() and _.last() to retrieve specific elements from the jQuery object. These are simple functions that have the equivalent functionality already implemented in jQuery — so I'm not advocating the reinvention of the wheel. The goal is to simply show that there's room for both libraries to collaborate.