What are The JavaScript Iteration Methods😱
In JavaScript, iteration methods are used to loop over or iterate through the elements of collections like arrays, objects, maps, and sets. These methods allow you to process, modify, or perform actions on each item in a collection. Here's an overview of the most commonly used iteration methods for different data structures.
1. Array Iteration Methods
These methods allow you to iterate over arrays and perform actions on each element.
forEach()
Executes a provided function once for each element in the array.
Does not return a new array (it is used for side effects like printing to the console or updating external variables).
const arr = [1, 2, 3];
arr.forEach((item, index) => {
console.log(index, item);
});
// Output:
// 0 1
// 1 2
// 2 3
map()
Returns a new array where each element is transformed by the provided function.
Useful for applying a function to each element and creating a new array.
const arr = [1, 2, 3];
const doubled = arr.map(x => x * 2);
console.log(doubled); // [2, 4, 6]
filter()
- Creates a new array with all elements that pass a given test (provided by a function).
const arr = [1, 2, 3, 4, 5];
const evens = arr.filter(x => x % 2 === 0);
console.log(evens); // [2, 4]
reduce()
Executes a reducer function (accumulator and current value) on each element in the array, and returns a single accumulated result.
Ideal for summing values, accumulating counts, or combining array elements.
const arr = [1, 2, 3, 4];
const sum = arr.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10
reduceRight()
- Similar to
reduce()
, but it processes the array from right to left.
const arr = [1, 2, 3, 4];
const sumRight = arr.reduceRight((acc, num) => acc + num, 0);
console.log(sumRight); // 10
some()
- Tests whether at least one element in the array passes the test implemented by the provided function.
const arr = [1, 2, 3, 4];
const hasEven = arr.some(x => x % 2 === 0);
console.log(hasEven); // true
every()
- Tests whether all elements in the array pass the test implemented by the provided function.
const arr = [1, 2, 3, 4];
const allEven = arr.every(x => x % 2 === 0);
console.log(allEven); // false
find()
Returns the first element in the array that satisfies the provided testing function.
Useful for finding a specific item.
const arr = [1, 2, 3, 4];
const found = arr.find(x => x > 2);
console.log(found); // 3
findIndex()
- Returns the index of the first element that satisfies the provided function.
const arr = [1, 2, 3, 4];
const index = arr.findIndex(x => x > 2);
console.log(index); // 2
sort()
- Sorts the elements of an array in place (modifies the array) based on a sorting function.
const arr = [4, 2, 3, 1];
arr.sort((a, b) => a - b);
console.log(arr); // [1, 2, 3, 4]
2. Object Iteration Methods
Although objects don’t have built-in iteration methods like arrays, you can use some methods and techniques to iterate through object properties.
for...in
Loop
Loops through the keys (property names) of an object.
Can be used to iterate over the object's enumerable properties (including inherited ones).
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(key, obj[key]);
}
// Output:
// a 1
// b 2
// c 3
Object.keys()
- Returns an array of the object's own enumerable property names (keys).
const obj = { a: 1, b: 2, c: 3 };
Object.keys(obj).forEach(key => {
console.log(key, obj[key]);
});
// Output:
// a 1
// b 2
// c 3
Object.values()
- Returns an array of the object's own enumerable property values.
const obj = { a: 1, b: 2, c: 3 };
Object.values(obj).forEach(value => {
console.log(value);
});
// Output:
// 1
// 2
// 3
Object.entries()
- Returns an array of key-value pairs (arrays) for the object's own enumerable properties.
const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj).forEach(([key, value]) => {
console.log(key, value);
});
// Output:
// a 1
// b 2
// c 3
3. Set and Map Iteration Methods
Set Iteration Methods
Sets are collections of unique values.
forEach()
: Similar to array iteration but for sets.
const set = new Set([1, 2, 3]);
set.forEach(value => {
console.log(value);
});
// Output:
// 1
// 2
// 3
values()
: Returns an iterator over the values in the set.
const set = new Set([1, 2, 3]);
const iterator = set.values();
console.log(iterator.next().value); // 1
entries()
: Returns an iterator over [value, value] pairs (since sets store only values, both elements are the same).
const set = new Set([1, 2, 3]);
const iterator = set.entries();
console.log(iterator.next().value); // [1, 1]
Map Iteration Methods
Maps are collections of key-value pairs, and they maintain the order of insertion.
forEach()
: Iterates over each key-value pair in the map.
const map = new Map([['a', 1], ['b', 2]]);
map.forEach((value, key) => {
console.log(key, value);
});
// Output:
// a 1
// b 2
keys()
: Returns an iterator for the map’s keys.
const map = new Map([['a', 1], ['b', 2]]);
const keys = map.keys();
console.log(keys.next().value); // 'a'
values()
: Returns an iterator for the map’s values.
const map = new Map([['a', 1], ['b', 2]]);
const values = map.values();
console.log(values.next().value); // 1
entries()
: Returns an iterator for the map’s key-value pairs.
const map = new Map([['a', 1], ['b', 2]]);
const entries = map.entries();
console.log(entries.next().value); // ['a', 1]
4. Iterators and Generators
Symbol.iterator
- Defines how an object should be iterated using methods like
for...of
.
const obj = {
values: [1, 2, 3],
[Symbol.iterator]() {
let index = 0;
const values = this.values;
return {
next() {
if (index < values.length) {
return { value: values[index++], done: false };
} else {
return { done: true };
}
}
};
}
};
for (const value of obj) {
console.log(value); // 1 2 3
}
Summary of Iteration Methods
Data Structure | Method(s) | Purpose |
Array | forEach() , map() , filter() , reduce() , some() , every() , find() , findIndex() | Iterate through elements, transform, or accumulate values |
Object | for...in , Object.keys() , Object.values() , Object.entries() | Iterate through keys or key-value pairs |
Set | forEach() , values() , entries() | Iterate through unique values |
Map | forEach() , keys() , values() , entries() | Iterate through key-value pairs |
These iteration methods are extremely helpful for working with collections in JavaScript.