Skip to main content

each()

each<T>(collection, iteratee): T[]

each<T>(collection, iteratee): T

Iterates over elements of collection and invokes iteratee for each element.

DEPRECATED

Use array.forEach() or for...of loop directly instead.


Type Parameters​

T: T​

The type of elements in the array, or the object type.


Parameters​

Overload 1:

collection: T[]​

The collection to iterate over.

iteratee: (value, index, array) => void​

The function invoked per iteration.

Overload 2:

collection: T​

The collection to iterate over.

iteratee: (value, key, object) => void​

The function invoked per iteration.


Returns: T[]​

The original collection.


See Also​


Since​

2.0.0


Also known as​

forEach (Lodash, es-toolkit, Remeda, Ramda, Effect) · ❌ (Radashi, Modern Dash, Antfu)


Example​

const numbers = [1, 2, 3, 4, 5];

// ❌ Deprecated approach
each(numbers, (value, index) => {
console.log(`Index ${index}: ${value}`);
});

// βœ… Recommended approach (for arrays)
numbers.forEach((value, index) => {
console.log(`Index ${index}: ${value}`);
});

// βœ… Alternative with for...of
for (const [index, value] of numbers.entries()) {
console.log(`Index ${index}: ${value}`);
}

// βœ… Recommended approach (for objects)
const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});

How it works?​

Iterates over elements of collection. Deprecated: Use array.forEach() directly.

Native Equivalent​

// ❌ each(arr, fn)
// βœ… arr.forEach(fn)

Use Cases​

Iterate over items for side effects πŸ“Œβ€‹

Execute a function for each element for logging or analytics.

const users = [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }];
users.forEach(user => console.log(`Processing: ${user.name}`));

Traverse object properties​

Iterate over all properties of an object.

const config = { apiUrl: "https://api.com", timeout: 5000 };
Object.entries(config).forEach(([key, value]) => {
if (value === undefined) console.warn(`${key} is undefined`);
});

Process form fields​

Iterate over elements for bulk operations.

const fields = document.querySelectorAll("input");
[...fields].forEach(field => field.value = "");