Get the first element of an array. Passing n will return the first N values in the array. Aliased as head and take. The guard check allows it to work with _.map.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
What is the use of the variable 'guard' in this underscore.js function?
If you look at the source code:
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
The guard check allows it to work with
_.map.
So if you have an array like this:
var a = [ [1, 2, 3], [4, 5, 6] ];
// put this array though _.map and _.first
_.map(a, _.first); // [1, 4]
If this wasn't the case you result would look like this:
[ [], [4] ]
Because of the arguments going into _.map:
_.map(['a', 'b', 'c'], function(val, key, obj) {
// key = 0, 1, 2
// val = a, b, c
// obj = ['a', 'b', 'c']
// the obj argument is why `guard` is truly and the first element in the array is returned rater than using [].slice
});
Its not beautiful but it allows it to work together:
_.first([1, 2, 3], 2) // [1, 2]
_.first([1, 2, 3], 2, true) // 1
_.first([1, 2, 3], 2, 3) // 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With