Appearance
Underscore
As discussed earlier, JavaScript is a functional programming language that supports higher-order functions and closures. Functional programming is powerful and allows for very concise code. For example, consider the map()
and filter()
methods of the Array
:
javascript
let a1 = [1, 4, 9, 16];
let a2 = a1.map(Math.sqrt); // [1, 2, 3, 4]
let a3 = a2.filter((x) => { return x % 2 === 0; }); // [2, 4]
Now, a problem arises: while Array
has map()
and filter()
methods, Object
does not have these methods. Additionally, older browsers like IE6–8 also lack these methods. What can we do?
Method 1: We can add these methods to Array.prototype
and similarly add mapObject()
and other methods to Object.prototype
.
Method 2: We can directly find a mature and reliable third-party open-source library to implement these operations uniformly.
We will choose Method 2 and use the third-party library called Underscore.
Just as jQuery unified the differences in DOM operations across various browsers, allowing us to manipulate the DOM easily, Underscore provides a comprehensive set of functional programming interfaces that facilitate functional programming in JavaScript.
When jQuery loads, it binds itself to the unique global variable $
, and Underscore does the same by binding itself to the unique global variable _
. This is also why it is called Underscore.
Using Underscore to implement the map()
operation looks like this:
javascript
let r = _.map([1, 2, 3], (x) => x * x);
console.log(r); // [1, 4, 9]
At first glance, this may seem slightly more complicated than using Array.map()
, but Underscore's map()
can also operate on Object
:
javascript
_.map({ a: 1, b: 2, c: 3 }, (v, k) => k + '=' + v); // ['a=1', 'b=2', 'c=3']
Later, we will provide a detailed introduction to the series of functional interfaces offered by Underscore.