Functional Programming with JavaScript Libraries: Ramda, Lodash, and Immutable.js


Functional programming is a popular paradigm in JavaScript development, emphasising immutability, pure functions, and higher-order functions. It promotes writing clean, concise, and maintainable code. To facilitate advanced functional programming techniques, several JavaScript libraries have emerged, providing powerful tools and utilities. In this article, we will explore three such libraries: Ramda, Lodash, and Immutable.js. We will dive into code examples, explain their features, and showcase the benefits they bring to functional programming in JavaScript.

Ramda: Functional Programming made Easy

Ramda is a powerful library that promotes functional programming in JavaScript. It focuses on immutability and provides a wide range of functions that operate on immutable data structures. One of its main strengths is its composability, allowing developers to build complex transformations by chaining multiple functions together.

Example

Let's take a look at more examples using Ramda −

// Example: Composing multiple functions with Ramda
const add = (a, b) => a + b;
const double = (n) => n * 2;
const subtractTen = (n) => n - 10;

const result = R.pipe(
   add,
   double,
   subtractTen
)(5, 3);

console.log(result); 

Explanation

In this example, we define three functions: add, double, and subtractTen. We then use R.pipe to compose them together. The input 5 and 3 are passed through the composed functions, resulting in the output 8.

Output

8

Ramda provides many more useful functions for various data manipulations, such as sorting, slicing, reducing, and more.

Example

Let's see an example of using R.sort −

// Example: Sorting an array with Ramda
const numbers = [3, 1, 4, 2, 5];

const sortedNumbers = R.sort((a, b) => a - b, numbers);

console.log(sortedNumbers);

Explanation

In this example, we use R.sort to sort the array of numbers in ascending order. The resulting array is [1, 2, 3, 4, 5].

Output

[1, 2, 3, 4, 5]

Lodash: The Swiss Army Knife of JavaScript

Lodash is a widely adopted utility library that provides many helpful functions for manipulating arrays, objects, and other data structures. While it's not purely functional, Lodash embraces functional programming concepts and allows developers to write code in a more functional style.

Example

Here's an example showcasing Lodash's capabilities −

// Example: Filtering an array with Lodash
const numbers = [1, 2, 3, 4, 5];

const filteredNumbers = _.filter(numbers, (n) => n % 2 === 0);

console.log(filteredNumbers); 

Explanation

In this example, we use _.filter to filter even numbers from the array. The resulting array contains [2, 4].

Output

[2, 4]

Lodash provides an extensive set of functions for array manipulation, object manipulation, string manipulation, and more. Let's see an example using _.groupBy.

Example 

// Example: Grouping objects by a property with Lodash
const books = [
   { title: 'JavaScript: The Good Parts', author: 'Douglas Crockford' },
   { title: 'Eloquent JavaScript', author: 'Marijn Haverbeke' },
   { title: 'JavaScript: The Definitive Guide', author: 'David Flanagan' },
   { title: 'You Don't Know JS', author: 'Kyle Simpson' }
];

const booksByAuthor = _.groupBy(books, 'author');

console.log(booksByAuthor);

Explanation

In this example, we use _.groupBy to group the books array by the author's name. The resulting object contains arrays of books grouped by the author's name.

Output

{
   'Douglas Crockford': [
      { title: 'JavaScript: The Good Parts', author: 'Douglas Crockford' }
   ],
   'Marijn Haverbeke': [
      { title: 'Eloquent JavaScript', author: 'Marijn Haverbeke' }
   ],
   'David Flanagan': [
      { title: 'JavaScript: The Definitive Guide', author: 'David Flanagan' }
   ],
   'Kyle Simpson': [
      { title: 'You Don't Know JS', author: 'Kyle Simpson' }
   ]
}

Immutable.js: Immutable Data Structures for JavaScript

Immutable.js is a library that provides immutable data structures, making it easier to enforce immutability in JavaScript. It offers persistent data structures, which means that modifications to existing data create new objects while reusing unchanged parts. This approach helps prevent unintended side effects and simplifies state management.

Example 

Consider the following example −

// Example: Manipulating an immutable list with Immutable.js
let list1 = Immutable.List([1, 2, 3]);
let list2 = list1.push(4);

console.log(list1.toArray());
console.log(list2.toArray());

Explanation

In this example, we create an Immutable.js List with three elements. We then use the push method to append a fourth element, creating a new list. The original list remains unchanged, while we obtain the modified list.

Output

[1, 2, 3]
[1, 2, 3, 4]

Immutable.js provides a range of data structures, including List, Map, Set, and more.

Example 

Let's explore another example using a Map −

// Example: Updating a value in an immutable Map with Immutable.js
let map1 = Immutable.Map({ name: 'John', age: 30 });
let map2 = map1.set('age', 31);

console.log(map1.toObject()); // Output: { name: 'John', age: 30 }
console.log(map2.toObject()); // Output: { name: 'John', age: 31 }

Explanation

In this example, we create an Immutable.js Map with a name and an age. We then use the set method to update the age value. Similar to the previous example, the original map remains unchanged, while a new map is created with the updated value.

Output

{ name: 'John', age: 30 }
{ name: 'John', age: 31 }

Conclusion

Functional programming with JavaScript libraries like Ramda, Lodash, and Immutable.js brings numerous benefits, including code readability, maintainability, and performance optimization. These libraries empower developers to embrace functional programming concepts while providing powerful tools for data manipulation, composition, and immutability.

Ramda simplifies functional programming with its composability, allowing developers to chain functions and create complex transformations. Lodash serves as a versatile utility library with functional programming support, offering a broad range of functions for data manipulation and manipulation of various data structures. Immutable.js provides immutable data structures, enforcing immutability and preventing unintended side effects.

Updated on: 25-Jul-2023

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements