0
# Lodash ForEach
1
2
Lodash ForEach is a standalone module providing the modern build of lodash's `_.forEach` utility function (also known as `_.each`). It enables iteration over arrays, objects, and strings with support for early termination and custom binding context, offering optimized performance by detecting array types and using specialized iteration strategies.
3
4
## Package Information
5
6
- **Package Name**: lodash.foreach
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.foreach`
10
11
## Core Imports
12
13
```javascript
14
var forEach = require('lodash.foreach');
15
```
16
17
ES6/ES2015:
18
```javascript
19
import forEach from 'lodash.foreach';
20
```
21
22
## Basic Usage
23
24
```javascript
25
var forEach = require('lodash.foreach');
26
// or import forEach from 'lodash.foreach';
27
28
// Array iteration
29
forEach([1, 2, 3], function(value, index, array) {
30
console.log(value);
31
});
32
// => 1 2 3
33
34
// Object iteration
35
forEach({ 'a': 1, 'b': 2 }, function(value, key, object) {
36
console.log(key + ': ' + value);
37
});
38
// => a: 1 b: 2
39
40
// String iteration
41
forEach('abc', function(char, index, string) {
42
console.log(char);
43
});
44
// => a b c
45
46
// With binding context
47
var context = { multiplier: 2 };
48
forEach([1, 2, 3], function(value) {
49
console.log(value * this.multiplier);
50
}, context);
51
// => 2 4 6
52
53
// Early exit by returning false
54
forEach([1, 2, 3, 4, 5], function(value) {
55
if (value === 3) return false;
56
console.log(value);
57
});
58
// => 1 2
59
```
60
61
## Capabilities
62
63
### ForEach Iteration
64
65
Iterates over elements of collection invoking iteratee for each element. The iteratee is bound to `thisArg` and invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning `false`.
66
67
```javascript { .api }
68
/**
69
* Iterates over elements of collection invoking iteratee for each element.
70
* The iteratee is bound to thisArg and invoked with three arguments:
71
* (value, index|key, collection). Iteratee functions may exit iteration
72
* early by explicitly returning false.
73
*
74
* @param {Array|Object|string} collection - The collection to iterate over
75
* @param {Function} [iteratee] - The function invoked per iteration
76
* @param {*} [thisArg] - The this binding of iteratee
77
* @returns {Array|Object|string} Returns collection
78
*/
79
function forEach(collection, iteratee, thisArg);
80
```
81
82
**Parameters:**
83
- `collection` (Array|Object|string): The collection to iterate over
84
- `iteratee` (Function, optional): The function invoked per iteration. If not provided, the collection is still returned unchanged
85
- `thisArg` (*, optional): The `this` binding of iteratee
86
87
**Returns:**
88
- (Array|Object|string): Returns the exact same reference to the original `collection` (not a copy)
89
90
**Behavior:**
91
- Objects with a "length" property are iterated like arrays (to avoid this behavior, use `_.forIn` or `_.forOwn`)
92
- Iteratee receives three arguments: (value, index|key, collection)
93
- Early exit is supported by explicitly returning `false` from iteratee
94
- **Performance optimization:** Arrays without `thisArg` use optimized array iteration path
95
- For all other cases, uses base collection iteration with callback binding
96
- Non-function iteratees are handled gracefully (collection is returned unchanged)
97
- Null or undefined collections are handled safely
98
99
**Usage Examples:**
100
101
```javascript
102
var forEach = require('lodash.foreach');
103
104
// Basic array iteration with return value
105
var result = forEach([1, 2], function(n) {
106
console.log(n);
107
});
108
// => logs each value from left to right and returns the array
109
// result equals [1, 2]
110
111
// Object iteration with guaranteed behavior
112
forEach({ 'user1': { 'active': true }, 'user2': { 'active': false } },
113
function(user, key) {
114
if (user.active) {
115
console.log(key + ' is active');
116
}
117
}
118
);
119
120
// String character iteration
121
forEach('hello', function(char, index) {
122
console.log('char at ' + index + ': ' + char);
123
});
124
125
// Early termination example
126
var found = false;
127
forEach([1, 2, 3, 4, 5], function(value) {
128
if (value === 3) {
129
found = true;
130
return false; // Exit early
131
}
132
console.log('Processing: ' + value);
133
});
134
// => Processing: 1, Processing: 2
135
136
// Performance optimization - no thisArg binding for arrays
137
forEach(largeArray, function(item, index) {
138
// Fast array iteration path
139
processItem(item);
140
});
141
142
// Binding context for complex operations
143
var processor = {
144
prefix: '[LOG]',
145
process: function(items) {
146
forEach(items, function(item) {
147
console.log(this.prefix + ' ' + item);
148
}, this);
149
}
150
};
151
152
// Array-like objects with length property are treated as arrays
153
var arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
154
forEach(arrayLike, function(value, index) {
155
console.log(index + ': ' + value);
156
});
157
// => 0: a, 1: b, 2: c
158
159
// Edge case handling - non-function iteratee
160
var result = forEach([1, 2, 3]); // No iteratee provided
161
console.log(result); // => [1, 2, 3] (original array returned)
162
163
// Edge case handling - null/undefined collections
164
forEach(null, function() {}); // => null (handled safely)
165
forEach(undefined, function() {}); // => undefined (handled safely)
166
167
// Demonstrating that original reference is returned
168
var original = [1, 2, 3];
169
var returned = forEach(original, function(n) { console.log(n); });
170
console.log(original === returned); // => true (same reference)
171
```