Example 1 — Official Array Iteration
Visit every number in turn (docs use alert; we collect for clarity).
var seen = [];
_.each([1, 2, 3], function (n) {
seen.push(n);
});
seen;
// → [1, 2, 3]
How It Works
- Walk. Underscore calls the iteratee for
1, then 2, then 3. - Args. Each call is
(element, index, list). - Side effect. We push into
seen — classic _.each use. - Return.
_.each itself returns the original array.
Example 2 — Official Object Iteration
Plain objects yield values (and keys) — not just arrays.
var pairs = [];
_.each({ one: 1, two: 2, three: 3 }, function (value, key) {
pairs.push(key + "=" + value);
});
pairs;
// → ["one=1", "two=2", "three=3"]
["one=1","two=2","three=3"]
How It Works
- Object mode. Iteratee args are
(value, key, list). - Value first. Unlike jQuery’s
$.each(index, value). - Own keys. Underscore walks the object’s own enumerable properties.
- Docs sample. Same collection as the official object demo.
Example 3 — Bind this with Context
Pass a third argument so methods use the right this.
var logger = {
prefix: "n=",
lines: [],
add: function (n) {
this.lines.push(this.prefix + n);
}
};
_.each([1, 2, 3], logger.add, logger);
logger.lines;
// → ["n=1", "n=2", "n=3"]
How It Works
- Method ref.
logger.add alone would lose this. - Context. Third arg binds
this to logger. - Calls. Each number is appended as
"n=…". - Alternative.
_.each(list, function (n) { logger.add(n); }) also works.
Example 4 — Side Effects vs _.map
_.each for actions; _.map when you need a result array.
var total = 0;
_.each([10, 20, 30], function (n) {
total += n;
});
// total → 60
var doubled = _.map([10, 20, 30], function (n) {
return n * 2;
});
// doubled → [20, 40, 60]
_.forEach === _.each;
// → true
How It Works
- each. Mutates outer
total — a side effect. - map. Returns a new array of transformed values.
- Alias.
_.forEach is the same function as _.each. - Rule. Prefer
_.map when the return value matters.