As we mentioned, the various collection functions in Underscore really help us to navigate our way around JavaScript objects and arrays in a really easy and straightforward way. In this particular tutorial we’ll have a look at the each
function and how we can use it with arrays, objects, arrays with context, as well as objects with context. When we say with context, all we really mean is what the this keyword will be pointing to during particular portions of code execution. The each
function is really one of those bread and butter type functions that you just have to know, so let’s dig in now and get better at working with each
in Underscore.
_.each()
_.each() with Arrays
First off, we’ll have a look at working with a simple array with the each
function. In this first example we have a simply array of cars
. Let’s see if we can iterate over each car in the cars
array to do something interesting. The way we do this is to call the each
function and pass in the cars
array as the first parameter. The second parameter to the each
call is our iterator function. This function gets executed on each loop through the array, on each element of the array. When you go ahead and click the button to run the code, we can see four lines of output corresponding to each item in the cars
array. In looking at the iterator function signature, we have an element (refers to an element in the array), an index (the numerical index of each element), and the list argument which references the original data.
var cars = ['Tesla', 'Nissan', 'Chevy', 'Subaru'];
_.each(cars, function (element, index, list) {
var output = 'Element: ' + element + ', ' + 'Index: ' + index + ', ' + 'List Length: ' + list.length;
log(output, '#eacharraysunderscore');
});
Click Clear
.each() with an Object
This example will focus on seeing how each works when dealing with a JavaScript object. Now have a look at that sampleobject
and notice is has a FirstKey
of One
and SecondKey
of Two
. With our sampleobject
set up, we then make a call to the each
function, and you guessed it – pass that sampleobject
right in there as the first argument. So what do you want to do with that sampleobject
? Well, that is where our handy iterator function comes in to play (The anonymous function passed in as the second argument). In this example, our iterator has a signature of value
and key
. As such, we have access to those values within the iterator and we make use of them to print out some useful information about the object.
var sampleobject = {FirstKey: 'One', SecondKey: 'Two'};
_.each(sampleobject, function (value, key) {
var output = 'The value is '
+ value
+ ' where the key is ' + key;
log(output, '#eachobjectunderscore');
});
Click Clear
_.each() and Arrays With Context
Next up we’ll have a look at working with each
and arrays but setting the context as well. Go ahead and click the button to run the code and notice the output of
- Microsoft creates great products.
- Google creates great products.
- Amazon creates great products.
- Apple creates great products.
We can see that when we call the each
function, TechCompanies.names
is passed in as the first argument to the function. This object also has a nested function which we can see is named doStuff
. We make use of that familiar iterator function which takes in the element, index, and list. Notice that after the iterator function we in fact pass in TechCompanies
as the context. This binds the TechCompanies
object to the this
keyword inside the iterator. See how that works? This is what makes it possible to make the call to this.doStuff()
in the iterator, and it knows where to find that function. If there was no context passed, the this
keyword would be referencing the iterator function and that is not what we want in this case.
var TechCompanies;
TechCompanies = {
names: ['Microsoft', 'Google', 'Amazon', 'Apple'],
doStuff: function (company) {
return company + ' creates great products.';
}
};
_.each(TechCompanies.names, function (element, index, list) {
log(this.doStuff(element), '#eacharraycontextunderscore')
}, TechCompanies);
Click Clear
Object With Context
Finally, we can take a look at setting context with each when you’re dealing with an Object. If you give the code a run, you’ll see this output.
- This Tesla has Auto Pilot
- This Tesla has Summons Feature
- This Tesla has Ludicrous Mode
All great reason to go out and pick yourself up a nice Tesla. So this example makes use of two objects. The first object is the features object, and that holds all of the features of a cool car. The salesperson object contains functions such as getPitch and sellCar. In the call to each, we iterate over the features object, then again set up an iterator function as the second argument. We don’t finish there however, as we also pass in salesperson as the context to the each function. Therefore when we make a call to this.sellCar in the iterator, it knows to go look for that function inside the salesperson object since this is what was passed as the context.
var features, salesperson;
features = {
one: 'Auto Pilot',
two: 'Summons Feature',
three: 'Ludicrous Mode'
};
salesperson = {
getPitch: function () {
return 'This Tesla has ';
},
sellCar: function (msg) {
return this.getPitch()
+ msg;
}
};
_.each(features, function (value, key) {
log(this.sellCar(value), '#eachobjectcontextunderscore');
}, salesperson);
Click Clear
Underscore JS Each Function Summary
In this tutorial, we had a close look at working with each() in the underscore library. The four examples were definitely helpful in better understanding how each works with arrays and objects. We also came up to speed with setting the context properly when dealing with both arrays and objects.