Underscore.js Tutorial: Simplify JavaScript Array & Object Operations

目次

1. Introduction

JavaScript is an essential programming language for web development, but working with arrays and objects can easily make code complex. In particular, tasks such as data filtering and transformation often require cleaner, more efficient syntax.

That’s where the JavaScript library Underscore.js comes in. By using this library, even complex data operations can be written in a simple, readable way.

Why Underscore.js Stands Out

  1. More concise code
  • Operations that often become verbose in plain JavaScript can be expressed in just a few lines with Underscore.js.
  1. A rich set of convenient functions
  • It provides many features, including array operations, object handling, and function control.
  1. Lightweight and flexible
  • Because you can use only what you need, the performance impact can be kept to a minimum.

What You’ll Learn in This Article

  • How to set up Underscore.js
  • Core functions and practical examples
  • Real-world use cases that help in development

2. What Is Underscore.js?

Overview of Underscore.js

Underscore.js is a lightweight library that makes data manipulation in JavaScript easier. It offers a wide range of convenient functions designed mainly to streamline operations on arrays and objects, and it’s often described as a JavaScript utility toolkit.

JavaScript’s standard features are powerful, but code can become long and readability can suffer. Using Underscore.js helps address these issues, letting you write simpler, more maintainable code.

Key Features

  1. A wide variety of utility functions
  • It provides many functions, including array operations, object operations, and function control.
  1. Simple, readable code
  • Compared to traditional plain JavaScript patterns, it reduces boilerplate and improves readability.
  1. No dependencies
  • Because it doesn’t depend on other libraries, you can use it flexibly in many environments.
  1. Lightweight and fast
  • Its small size and low overhead make it a good fit even for modern web applications.

Underscore.js vs. Lodash

A frequently compared library is Lodash. Lodash builds on Underscore.js and expands its functionality, with differences such as the following.

AspectUnderscore.jsLodash
FunctionalityIncludes many core utility functionsOffers an even broader feature set
Modular usagePartially supportedFully modularized
PerformanceFastFast and further optimized

Which one you choose depends on your project requirements, but if you want a simple and lightweight library, Underscore.js is a strong choice.

How Can Underscore.js Help?

Underscore.js is especially useful in situations like these.

  1. Array data manipulation
  • It enables concise code for operations like filtering and mapping.
  1. Object manipulation
  • You can easily retrieve keys/values and merge elements, among other tasks.
  1. Function control
  • It makes it easy to implement controls like “run only once” or delayed execution.
  1. Leveraging utility helpers
  • You can also use it for sorting, randomization, and even as a simple templating engine.

3. Installation

In this section, we’ll walk through concrete steps to add Underscore.js to your project. You’ll learn both the CDN approach and how to install it locally by downloading files.

1. Using a CDN

A CDN (Content Delivery Network) is a convenient way to use a library by simply linking to a hosted file on the internet. You can use Underscore.js by adding the following code inside the <head> tag or at the end of the <body> tag in your HTML file.

Example: Adding to an HTML File

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>Underscore.jsの導入</title>
  <!-- Underscore.jsのCDNリンク -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
</head>
<body>
  <h1>Underscore.jsのテスト</h1>
  <script>
    // 動作確認コード
    const data = [1, 2, 3, 4, 5];
    const evenNumbers = _.filter(data, function(num) {
      return num % 2 === 0;
    });
    console.log(evenNumbers); // [2, 4]
  </script>
</body>
</html>

When you open this file in a browser, you can confirm that only even numbers are displayed in the Developer Tools console.

2. Installing with npm or yarn

By using npm or yarn, you can also use Underscore.js in a local environment or in a Node.js project.

Install with npm

npm install underscore

Install with yarn

yarn add underscore

Example Import in a JavaScript File

import _ from 'underscore';

const data = [10, 20, 30, 40];
const result = _.map(data, (num) => num * 2);
console.log(result); // [20, 40, 60, 80]

3. Downloading the File and Using It Locally

  1. Go to the official website (underscorejs.org).
  2. Download the latest JavaScript file from the “Download” section.
  3. Place the downloaded file in an appropriate folder within your project (e.g., js/).
  4. Link it in your HTML file using a script tag.
<script src="js/underscore-min.js"></script>

4. When Using a Module Bundler

If you use a module bundler such as Webpack or Parcel, you can also integrate Underscore.js easily.

Example: Webpack Setup

  1. Install it with npm.
npm install underscore
  1. Import it in your JavaScript file.
import _ from 'underscore';
  1. Bundle it as needed and use it in your project.

Troubleshooting

1. If you see “Uncaught ReferenceError: _ is not defined”

  • Underscore.js may not be loaded correctly. Double-check your CDN link or your import path.

2. If errors occur after installing with npm

  • Update Node.js and npm to the latest versions.

4. Basic Usage

In this section, we’ll introduce some of the core functions of Underscore.js along with practical examples. These functions are extremely useful for efficiently working with arrays and objects.

1. Iterating Over Arrays – _.each()

_.each() is a function used to iterate over arrays or objects.

Example

const numbers = [1, 2, 3, 4, 5];

// Output each element to the console
_.each(numbers, function(num) {
  console.log(num);
});

Output:

1  
2  
3  
4  
5  

Key Points:

  • It works not only with arrays, but also with objects.
  • The callback receives the element, its index, and the entire collection.

2. Mapping Arrays – _.map()

_.map() applies a function to each element of an array and returns a new array.

Example

const numbers = [1, 2, 3, 4, 5];

// Double each element
const doubled = _.map(numbers, function(num) {
  return num * 2;
});

console.log(doubled);

Output:

[2, 4, 6, 8, 10]

3. Finding the First Matching Element – _.find()

_.find() returns the first element that matches a given condition.

Example

const numbers = [1, 2, 3, 4, 5];

// Find the first element greater than or equal to 3
const result = _.find(numbers, function(num) {
  return num >= 3;
});

console.log(result);

Output:

3

4. Filtering All Matching Elements – _.filter()

_.filter() extracts all elements that match a condition and returns them as a new array.

Example

const numbers = [1, 2, 3, 4, 5];

// Extract only even numbers
const evens = _.filter(numbers, function(num) {
  return num % 2 === 0;
});

console.log(evens);

Output:

[2, 4]

5. Shuffling Array Elements – _.shuffle()

_.shuffle() randomly rearranges the elements of an array.

Example

const numbers = [1, 2, 3, 4, 5];

// Randomly shuffle the array
const shuffled = _.shuffle(numbers);

console.log(shuffled);

Output: (example)

[3, 5, 1, 4, 2]

6. Removing Duplicate Elements – _.uniq()

_.uniq() removes duplicate values from an array.

Example

const numbers = [1, 2, 2, 3, 4, 4, 5];

// Remove duplicate elements
const uniqueNumbers = _.uniq(numbers);

console.log(uniqueNumbers);

Output:

[1, 2, 3, 4, 5]

Summary

So far, we’ve covered the basic functions of Underscore.js along with practical examples.

  • _.each() for iterating over elements
  • _.map() for creating new arrays
  • _.find() and _.filter() for extracting matching elements
  • _.shuffle() for randomizing elements
  • _.uniq() for removing duplicates

5. Advanced Usage

In this section, we’ll explore more advanced Underscore.js functions and practical use cases. These features allow for more sophisticated data manipulation and analysis.

1. Sorting Arrays – _.sortBy()

_.sortBy() sorts array elements based on a specified key or condition.

Example

const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 20 },
  { name: 'Charlie', age: 30 }
];

// Sort by age
const sortedUsers = _.sortBy(users, 'age');

console.log(sortedUsers);

Output:

[
  { name: 'Bob', age: 20 },
  { name: 'Alice', age: 25 },
  { name: 'Charlie', age: 30 }
]

2. Grouping Arrays – _.groupBy()

_.groupBy() groups array elements based on a specified key or condition.

Example

const numbers = [1.1, 2.3, 2.4, 3.5, 4.7];

// Group by integer part
const grouped = _.groupBy(numbers, function(num) {
  return Math.floor(num);
});

console.log(grouped);

Output:

{
  1: [1.1],
  2: [2.3, 2.4],
  3: [3.5],
  4: [4.7]
}

3. Aggregating Data – _.countBy()

_.countBy() is a convenient function for aggregating data.

Example

const words = ['apple', 'banana', 'apricot', 'blueberry'];

// Count by first letter
const counts = _.countBy(words, function(word) {
  return word[0];
});

console.log(counts);

Output:

{
  a: 2,
  b: 2
}

Summary

In this section, we covered more advanced Underscore.js usage.

  • _.sortBy() for sorting arrays
  • _.groupBy() and _.countBy() for categorizing and aggregating data

6. Object Operations

In this section, we’ll introduce useful functions for working with objects in Underscore.js. These functions help efficiently handle object properties and values.

1. Retrieving Object Keys and Values

Get Keys – _.keys()

const person = { name: 'Alice', age: 25, city: 'Tokyo' };

const keys = _.keys(person);
console.log(keys);

Output:

['name', 'age', 'city']

Get Values – _.values()

const values = _.values(person);
console.log(values);

Output:

['Alice', 25, 'Tokyo']

2. Cloning Objects – _.clone()

_.clone() creates a shallow copy of an object.

const original = { name: 'Alice', age: 25 };
const clone = _.clone(original);

clone.age = 30; // Modify the clone
console.log(original.age); // 25
console.log(clone.age);    // 30

Summary

In this section, we explained how to work with objects using Underscore.js.

7. Function Operations

In this section, we’ll explain how to effectively work with functions using Underscore.js. These features are useful for controlling execution and improving performance.

1. Binding Functions – _.bind()

_.bind() binds a specific object to this when a function is executed.

Example

const person = {
  name: 'Alice',
  greet: function(greeting) {
    return `${greeting}, my name is ${this.name}`;
  }
};

const boundGreet = _.bind(person.greet, person);

console.log(boundGreet('Hello')); // Hello, my name is Alice

2. Delayed Execution – _.delay()

_.delay() delays the execution of a function by a specified amount of time.

Example

_.delay(function(message) {
  console.log(message);
}, 2000, 'Displayed after 2 seconds');

Output: (after 2 seconds)

Displayed after 2 seconds

3. Execute Only Once – _.once()

_.once() ensures that a function is executed only once. Subsequent calls are ignored.

Example

const initialize = _.once(function() {
  console.log('Initialization complete');
});

initialize(); // Executed
initialize(); // Ignored

4. Memoization – _.memoize()

_.memoize() caches the result of a function and skips recalculation when called again with the same arguments.

Example

const factorial = _.memoize(function(n) {
  return n <= 1 ? 1 : n * factorial(n - 1);
});

console.log(factorial(5)); // Calculated
console.log(factorial(5)); // Retrieved from cache

5. Throttling Function Execution – _.throttle()

_.throttle() limits how often a function can be executed.

Example

const log = _.throttle(function() {
  console.log('Processing...');
}, 2000);

// Simulate continuous events
setInterval(log, 500); // Executes only once every 2 seconds

Summary

In this section, we explored function-related utilities in Underscore.js.

  • _.bind() to fix the this context
  • _.delay() for delayed execution
  • _.once() for one-time execution
  • _.memoize() for caching results
  • _.throttle() to optimize execution frequency

8. Utility Functions

In this section, we’ll introduce convenient utility functions provided by Underscore.js. These functions are useful in many situations, including data handling, random generation, and templating.

1. Generating Random Numbers – _.random()

_.random() generates a random integer or floating-point number within a specified range.

Example

console.log(_.random(1, 10)); // Integer
console.log(_.random(1, 10, true)); // Floating-point

2. Checking for Empty Values – _.isEmpty()

_.isEmpty() checks whether an array, object, or string is empty.

Example

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

3. Creating Templates – _.template()

_.template() is used to create string templates.

Example

const template = _.template('Hello, <%= name %>!');
console.log(template({ name: 'Alice' }));

Output:

Hello, Alice!

Summary

In this section, we covered utility functions in Underscore.js.

  • _.random() for generating random numbers
  • _.isEmpty() for checking data state
  • _.template() for simple templating

9. Conclusion

In this article, we covered Underscore.js from basic usage to more advanced techniques. This library is extremely useful for simplifying data manipulation in JavaScript and writing efficient, maintainable code.

Key Takeaways

  1. Basic usage – Learned core functions for array and object manipulation.
  2. Advanced usage – Explored grouping, sorting, and aggregation.
  3. Function utilities – Covered execution control and memoization.
  4. Utility helpers – Introduced random generation and templating.

Final Thoughts

Underscore.js is a powerful tool that makes JavaScript development more efficient and approachable. Use this article as a reference and try applying it in your own projects. Continued hands-on practice will help you further improve your skills.

Frequently Asked Questions (FAQ)

Q1: Is Underscore.js free to use?

A: Yes. Underscore.js is released under the MIT license and can be used free of charge, including in commercial projects.

Q2: What is the difference between Underscore.js and Lodash?

A: Underscore.js is a simple and lightweight utility library. Lodash builds on Underscore.js with additional features, performance optimizations, and stronger modularization. Choose based on your project’s requirements.

Q3: Is Underscore.js unnecessary with modern JavaScript (ES6+)?

A: ES6+ provides many native features for array and object operations, but Underscore.js is still useful for cross-browser compatibility and concise syntax, especially in legacy projects.

Q4: What types of projects are suitable for Underscore.js?

A: It works well for small to medium-sized projects and applications where code simplicity is important. It’s especially helpful when you need lightweight utilities without heavy dependencies.

Q5: How can I install Underscore.js?

A: You can install it using any of the following methods.

  1. Add via CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
  1. Install with npm:
npm install underscore
  1. Install with yarn:
yarn add underscore

Choose the method that best fits your environment.

Q6: Where can I find the official documentation?

A: You can find it on the official website:
Underscore.js Official Website

Q7: Can Underscore.js be used in large-scale projects?

A: Yes, it can. However, for large projects, Lodash is often recommended due to its modular structure and additional optimizations. Underscore.js remains ideal for lightweight use cases.

Q8: Are there alternatives for function execution control?

A: Yes. Modern JavaScript offers alternatives such as setTimeout(), setInterval(), Promise, and async/await. However, Underscore.js functions like _.throttle() and _.debounce() allow for cleaner and more concise implementations.

Q9: Are there any caveats when using Underscore.js?

A:

  1. Avoid unnecessary dependencies when native JavaScript features are sufficient.
  2. Keep versions up to date to minimize security risks.
  3. Consider migrating to Lodash depending on project scale.

Q10: Is Underscore.js recommended as a template engine?

A: _.template() is convenient for simple use cases, but for more advanced templating needs, dedicated libraries such as Handlebars.js or EJS are recommended.

広告