目次
- 1 1. Introduction
- 2 2. What is Underscore.js?
- 3 3. How to Install
- 4 4. Basic Usage
- 5 5. Advanced Usage
- 6 6. Object Operations
- 7 7. Function Operations
- 8 8. Utility Functions
- 9 9. Conclusion
- 10 Frequently Asked Questions (FAQ)
- 10.1 Q1: Is Underscore.js free to use?
- 10.2 Q2: What’s the difference between Underscore.js and Lodash?
- 10.3 Q3: Is Underscore.js unnecessary with modern JavaScript (ES6+)?
- 10.4 Q4: What types of projects are best suited for Underscore.js?
- 10.5 Q5: How do I install Underscore.js?
- 10.6 Q6: Where can I find the official documentation?
- 10.7 Q7: Can Underscore.js be used in large projects?
- 10.8 Q8: Are there other ways to control function execution?
- 10.9 Q9: Are there any caveats when using Underscore.js?
- 10.10 Q10: Is _.template() recommended as a template engine?
1. Introduction
JavaScript is an essential programming language for web development, but working with arrays and objects can often make the code complex. Especially for operations such as filtering and transforming data, concise and efficient code is highly desirable. This is where the JavaScript library Underscore.js becomes helpful. By using this library, you can simplify the way complex data manipulations are written.The Benefits of Underscore.js
- Cleaner Code
- With traditional JavaScript, certain processes tend to become verbose, but with Underscore.js, they can often be written in just a few lines.
- Rich Set of Utility Functions
- It provides numerous features for array manipulation, object handling, and function control.
- Lightweight and Flexible
- You can use only the functions you need, keeping performance overhead to a minimum.
What You Will Learn in This Article
- How to set up Underscore.js
- Basic functions and practical examples
- Real-world use cases for development
2. What is Underscore.js?
Overview of Underscore.js
Underscore.js is a lightweight JavaScript library designed to simplify data manipulation. It provides a wide range of utility functions mainly for working efficiently with arrays and objects, often referred to as a JavaScript utility toolkit. While JavaScript itself has powerful built-in features, code can sometimes become lengthy or difficult to read. By using Underscore.js, you can solve these issues and write cleaner, more maintainable code.Key Features
- Comprehensive Utility Functions
- It offers functions for array manipulation, object handling, and function control, among others.
- Simplified, Readable Code
- Compared to traditional JavaScript, it reduces boilerplate and improves readability.
- No Dependencies
- It doesn’t rely on other libraries, making it flexible for integration.
- Lightweight and Fast
- Its small size and minimal performance impact make it suitable even for modern web applications.
Underscore.js vs. Lodash
A commonly compared library to Underscore.js is Lodash. Lodash was built on Underscore.js and extends its capabilities. Here are some differences:Feature | Underscore.js | Lodash |
---|---|---|
Functionality | Provides many basic utility functions | Expanded functionality with more features |
Modular Support | Partially supported | Fully modular |
Performance | Fast | Fast and further optimized |
When is Underscore.js Useful?
Underscore.js shines in the following scenarios:- Working with Arrays
- Perform filtering, mapping, and other array operations with concise syntax.
- Handling Objects
- Easily retrieve keys, values, or merge object properties.
- Controlling Functions
- Implement one-time execution, delayed execution, and other function control patterns with ease.
- Utility Functions
- Use it for sorting, randomization, or even as a simple template engine.
3. How to Install
In this section, we’ll go through the specific steps for adding Underscore.js to your project. We’ll cover using a CDN, installing via npm or yarn, downloading files manually, and integrating with module bundlers.1. Using a CDN
A CDN (Content Delivery Network) allows you to use libraries hosted on the internet by simply adding a link. Insert the following code into 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="en">
<head>
<meta charset="UTF-8">
<title>Using Underscore.js</title>
<!-- Underscore.js CDN Link -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
</head>
<body>
<h1>Testing Underscore.js</h1>
<script>
// Test code
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 opened in a browser, the developer console will display only the even numbers.2. Installing with npm or yarn
You can also install Underscore.js in your local environment or Node.js project.Using npm
npm install underscore
Using yarn
yarn add underscore
Import Example in JavaScript
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
- Go to the official website: underscorejs.org
- Download the latest JavaScript file from the “Download” section.
- Place the downloaded file in your project folder (e.g.,
js/
). - Link it in your HTML using a script tag.
<script src="js/underscore-min.js"></script>
4. Using a Module Bundler
If you’re using Webpack or Parcel, it’s just as easy:Example with Webpack
- Install via npm:
npm install underscore
- Import in your JavaScript file:
import _ from 'underscore';
- Bundle and use as needed.
Troubleshooting
1. “Uncaught ReferenceError: _ is not defined”- Underscore.js may not be loaded correctly. Double-check your CDN link or import path.
- Ensure Node.js and npm are updated to the latest version.
4. Basic Usage
In this section, we’ll introduce some of the core functions of Underscore.js with examples. These functions are particularly useful for simplifying array and object operations.1. Iterating Over Arrays – _.each()
_.each()
iterates over arrays or objects.Example
const numbers = [1, 2, 3, 4, 5];
// Print each element to the console
_.each(numbers, function(num) {
console.log(num);
});
Output:1
2
3
4
5
Key Points:- Works with both arrays and objects.
- The callback receives the element, 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 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 Elements – _.filter()
_.filter()
extracts all elements that match a condition into a new array.Example
const numbers = [1, 2, 3, 4, 5];
// Get only even numbers
const evens = _.filter(numbers, function(num) {
return num % 2 === 0;
});
console.log(evens);
Output:[2, 4]
5. Shuffling Elements – _.shuffle()
_.shuffle()
randomizes the order of elements in an array.Example
const numbers = [1, 2, 3, 4, 5];
// Shuffle the array
const shuffled = _.shuffle(numbers);
console.log(shuffled);
Output: (example)[3, 5, 1, 4, 2]
6. Removing Duplicates – _.uniq()
_.uniq()
removes duplicate elements from an array.Example
const numbers = [1, 2, 2, 3, 4, 4, 5];
// Remove duplicates
const uniqueNumbers = _.uniq(numbers);
console.log(uniqueNumbers);
Output:[1, 2, 3, 4, 5]
Summary
So far, we’ve looked at some of the fundamental functions of Underscore.js:_.each()
for iteration_.map()
for creating new arrays_.find()
and_.filter()
for conditional matching_.shuffle()
for randomizing elements_.uniq()
for removing duplicates
5. Advanced Usage
In this section, we’ll explore more advanced functions in Underscore.js. These allow for more powerful data manipulation and analysis.1. Sorting Arrays – _.sortBy()
_.sortBy()
sorts an array based on a given 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 Data – _.groupBy()
_.groupBy()
groups elements in an array based on a 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. Counting Data – _.countBy()
_.countBy()
makes it easy to count items based on a condition.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 advanced use cases of Underscore.js:_.sortBy()
for sorting arrays_.groupBy()
and_.countBy()
for grouping and counting data
6. Object Operations
In this section, we’ll cover useful Underscore.js functions for working with objects. These functions make it easier to process keys, values, and object properties efficiently.1. Retrieving 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 introduced object-related functions in Underscore.js:_.keys()
and_.values()
for retrieving keys and values_.clone()
for creating shallow copies
7. Function Operations
In this section, we’ll explore how Underscore.js helps you control and optimize function behavior. These utilities are especially useful for execution control and performance tuning.1. Binding Functions – _.bind()
_.bind()
binds a function to a specific object, ensuring this
always refers to that object.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. Delaying 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. Running Once – _.once()
_.once()
ensures a function runs only the first time it’s called.Example
const initialize = _.once(function() {
console.log('Initialization complete');
});
initialize(); // Runs
initialize(); // Ignored
4. Memoization – _.memoize()
_.memoize()
caches a function’s results, skipping recomputation for the same inputs.Example
const factorial = _.memoize(function(n) {
return n <= 1 ? 1 : n * factorial(n - 1);
});
console.log(factorial(5)); // Computed
console.log(factorial(5)); // Retrieved from cache
5. Throttling Execution – _.throttle()
_.throttle()
ensures a function is executed at most once within a given time interval.Example
const log = _.throttle(function() {
console.log('Processing...');
}, 2000);
// Simulate rapid events
setInterval(log, 500); // Executes only once every 2 seconds
Summary
This section introduced function-related utilities in Underscore.js:_.bind()
for fixingthis
_.delay()
for delayed execution_.once()
for one-time initialization_.memoize()
for caching results_.throttle()
for rate-limiting execution
8. Utility Functions
In this section, we’ll cover some of the handy utility functions provided by Underscore.js. These functions can be applied in a wide range of situations such as generating random values, checking data states, or working with templates.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 simple string templates.Example
const template = _.template('Hello, <%= name %>!');
console.log(template({ name: 'Alice' }));
Output:Hello, Alice!
Summary
Here are the utility functions we introduced:_.random()
for generating random numbers_.isEmpty()
for checking if data structures are empty_.template()
for creating simple templates
9. Conclusion
In this article, we’ve explored Underscore.js from the basics to more advanced use cases. This library is highly effective for simplifying data manipulation and writing efficient, maintainable JavaScript code.Recap
- Basic Usage – Learned core functions for working with arrays and objects.
- Advanced Usage – Covered classification, sorting, and aggregation of data.
- Function Operations – Explained optimization with execution control and memoization.
- Utility Functions – Introduced randomization, emptiness checks, and template creation.
Final Thoughts
Underscore.js is a powerful tool that makes JavaScript development more efficient and easier to manage. Use this article as a guide to incorporate it into your projects. Keep practicing to sharpen your skills further.Frequently Asked Questions (FAQ)
Q1: Is Underscore.js free to use?
A: Yes. Underscore.js is provided under the MIT License, and it’s free for both personal and commercial use.Q2: What’s the difference between Underscore.js and Lodash?
A: Underscore.js is a simple, lightweight utility library. Lodash is based on Underscore.js but extends functionality, offering better performance and full modularity. The choice depends on project requirements.Q3: Is Underscore.js unnecessary with modern JavaScript (ES6+)?
A: While ES6+ includes powerful array and object methods, Underscore.js remains useful for cross-browser compatibility, concise syntax, and working with legacy code.Q4: What types of projects are best suited for Underscore.js?
A: Small to medium-sized projects or applications that prioritize code simplicity. It’s especially useful when you want lightweight utilities for quick data operations.Q5: How do I install Underscore.js?
A: You can install it in multiple ways:- CDN link:
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
- npm:
npm install underscore
- yarn:
yarn add underscore
Q6: Where can I find the official documentation?
A: The official documentation is available here: Underscore.js Official WebsiteQ7: Can Underscore.js be used in large projects?
A: Yes, though for larger projects Lodash is often recommended due to its modularization and performance optimizations. Still, Underscore.js works well for small and medium-scale needs.Q8: Are there other ways to control function execution?
A: Yes. Modern JavaScript supportssetTimeout()
, setInterval()
, Promise
, and async/await
. However, Underscore.js provides _.throttle()
and _.debounce()
for concise and efficient implementations.Q9: Are there any caveats when using Underscore.js?
A:- Be mindful not to overuse it where native ES6 features are sufficient.
- Always use the latest version to avoid security issues.
- For larger projects, consider Lodash as an alternative.
Q10: Is _.template()
recommended as a template engine?
A: _.template()
is convenient for simple templating. For advanced needs, consider dedicated libraries such as Handlebars.js or EJS.広告