The Ultimate Guide to Using Underscore Js for Efficient JavaScript Development

Introduction to Underscore.js

Underscore.js is a powerful library that provides a variety of functional programming helpers without extending any built-in objects. It is designed to give developers a versatile toolkit of utilities to improve their JavaScript workflows.

Commonly Used Underscore API Methods

1. _.map

Transforms each item in an array or object using a function, returning a new array.

  const doubled = _.map([1, 2, 3], function(num) { return num * 2; });
  console.log(doubled); // [2, 4, 6]

2. _.reduce

Reduces a list into a single value by iteratively combining each item with an accumulator.

  const sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num; }, 0);
  console.log(sum); // 6

3. _.filter

Returns an array of items that pass a given test function.

  const evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 === 0; });
  console.log(evens); // [2, 4, 6]

4. _.find

Returns the first item that matches the test function, otherwise undefined.

  const firstEven = _.find([1, 2, 3, 4], function(num) { return num % 2 === 0; });
  console.log(firstEven); // 2

5. _.uniq

Returns a duplicate-free version of an array.

  const uniqueArray = _.uniq([1, 2, 1, 3, 1, 4]);
  console.log(uniqueArray); // [1, 2, 3, 4]

6. _.sortBy

Returns a sorted list based on the criterion.

  const sorted = _.sortBy([1, 3, 2, 5, 4], function(num) { return num; });
  console.log(sorted); // [1, 2, 3, 4, 5]

7. _.pluck

Extracts a list of property values from an array of objects.

  const friends = [{ name: 'John' }, { name: 'Jane' }, { name: 'Jack' }];
  const names = _.pluck(friends, 'name');
  console.log(names); // ['John', 'Jane', 'Jack']

8. _.range

Generates an array containing a range of numbers.

  const rangeArray = _.range(5);
  console.log(rangeArray); // [0, 1, 2, 3, 4]

9. _.extend

Copies all properties from source objects to a destination object.

  const source = { a: 1, b: 2 };
  const target = {};
  _.extend(target, source);
  console.log(target); // { a: 1, b: 2 }

10. _.isEmpty

Checks if an object or array is empty.

  console.log(_.isEmpty([])); // true
  console.log(_.isEmpty({})); // true
  console.log(_.isEmpty([1, 2, 3])); // false

Sample Application Using Underscore.js

We’ll build a simple todo list application demonstrating some of the methods mentioned above.

  const todos = [
    { title: 'Do laundry', completed: false },
    { title: 'Buy groceries', completed: true },
    { title: 'Write code', completed: false }
  ];

  // Get titles of all todos
  const titles = _.pluck(todos, 'title');
  console.log('Titles:', titles);

  // Sort todos by completion status
  const sortedTodos = _.sortBy(todos, 'completed');
  console.log('Sorted Todos:', sortedTodos);

  // Find the first incomplete todo
  const firstIncomplete = _.find(todos, function(todo) {
    return !todo.completed;
  });
  console.log('First Incomplete Todo:', firstIncomplete);

  // Display completed todos
  const completedTodos = _.filter(todos, function(todo) {
    return todo.completed;
  });
  console.log('Completed Todos:', completedTodos);

  // Check if the todo list is empty
  const isEmpty = _.isEmpty(todos);
  console.log('Is Todo List Empty?:', isEmpty);

Using Underscore.js significantly simplifies common JavaScript tasks, making your code cleaner and more readable.

Hash: 40321bd36a95181f24647a34ee65297fd80a88d7c98b31c96efe0db43867a0e5

Leave a Reply

Your email address will not be published. Required fields are marked *