JavaScript provides the following methods to loop through arrays.
for()
Arrays can be looped through using the for
loop.
Example:
const colors = ["red", "orange", "blue", "green", "white"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
// Output:
// red
// orange
// blue
// green
// white
forEach()
The forEach()
loop calls a function once for each element of the array.
Example:
const colors = ["red", "orange", "blue", "green", "white"];
colors.forEach((color) => console.log(color));
// Output:
// red
// orange
// blue
// green
// white
map()
The map()
method creates a new array by performing a function on each element of the array.
Syntax:
const newArray = array.map(callback);
- The callback runs once for each element.
- It does not modify the original array.
- The result of each callback becomes an element in the new array.
Example:
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map((num) => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
Here,
num => num * num
squares each number.map()
creates a new array of squared values.
filter()
The filter()
method creates a new array by filtering array elements based on a condition.
It does not change the original array. It creates a new one.
Syntax:
const newArray = array.filter(callback);
Here,
- The
filter()
method takes a callback function as an argument. This function is executed for each element of the array. - If the condition in the callback function returns
true
, the element is added to the new array. If it returnsfalse
, the element is skipped.
Example:
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6]
Here,
num % 2 === 0
checks if a number is even.- Only even numbers pass the condition and are added to the new array.
If no elements satisfy the condition, filter()
returns an empty array.
Example:
const nums = [1, 3, 5];
const greaterThan10 = nums.filter((num) => num > 10);
console.log(greaterThan10); // Output: []
reduce()
The reduce()
method can be used to reduce an array to a single value by performing a function on each element of the array.
Syntax:
array.reduce((accumulator, currentValue, currentIndex, array) => {
// function logic
}, initialValue);
accumulator
: Holds the result of the previous computation.currentValue
: The current element being processed.currentIndex
(optional): The index of the current element.array
(optional): The array being traversed.initialValue
(optional): The starting value for the accumulator.
Example:
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 10
Here,
- Starts with
acc = 0
(initial value). - Adds each element to
acc
:0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 10
- So the output is 10.
for...of
The for...of
loop can be used to get the values from an array.
Example:
const colors = ["red", "orange", "blue", "green", "white"];
for (color of colors) {
console.log(color);
}
// Output:
// red
// orange
// blue
// green
// white
for...in
The for...in
loop can be used to get the keys from an array.
Example:
const colors = ["red", "orange", "blue", "green", "white"];
for (color in colors) {
console.log(color);
}
// Output:
// 0
// 1
// 2
// 3
// 4
Note: This is not recommended for arrays. Because it iterates over all enumerable properties, not just array elements.
entries()
The entries() method returns a new iterator object that contains [index, value]
pairs for each array element.
Example:
const arr = ["a", "b", "c"];
const iterator = arr.entries();
for (const [index, value] of iterator) {
console.log(index, value);
}
// Output:
// 0 "a"
// 1 "b"
// 2 "c"
You can use this to loop over both the index and value of an array easily.
keys()
The keys() method returns a new iterator object containing the keys (indexes) for each element in the array.
Example:
const arr = ["a", "b", "c"];
const iterator = arr.keys();
for (const key of iterator) {
console.log(key);
}
// Output:
// 0
// 1
// 2
values()
The values() method returns a new iterator object containing the values for each element in the array.
Example:
const arr = ["a", "b", "c"];
const iterator = arr.values();
for (const value of iterator) {
console.log(value);
}
// Output:
// "a"
// "b"
// "c"
find()
The find()
method returns the first value of an element based on a condition.
Syntax:
array.find(callback);
- The
callback
function runs for each element. - It stops and returns the first element for which the callback returns true.
- If no element satisfies the condition, it returns
undefined
.
Example: 1
const arr = [1, 2, 3, 4, 5, 6];
const evenNumber = arr.find((num) => num % 2 === 0);
console.log(evenNumber); // Output: 2
Here,
- It checks each number to see if it’s even.
- The first even number is 2, so
find()
returns 2.
Example: 2
const arr2 = [4, 3, 6];
const evenNumber2 = arr2.find((num) => num % 2 === 0);
console.log(evenNumber2); // Output: 4
Here, the first even number is 4, so it returns 4.
findIndex()
The findIndex()
method returns the first index of an element based on a condition.
Example:
const arr = [1, 3, 13, 5, 2, 6];
const evenNumber = arr.findIndex((num) => num % 2 === 0);
console.log(evenNumber); // Output: 4
Here, the first even number is 2, which is at index 4, so findIndex()
returns 4.
some()
The some()
method checks if at least one element in the array passes a condition (callback function). It returns true if any element passes, otherwise false.
It does not change the array.
Example:
const arr = [1, 2, 3, 4];
const hasEven = arr.some((num) => num % 2 === 0);
console.log(hasEven); // Output: true
Here, 2 and 4 are even, so it returns true.
every()
The every()
method checks if all elements in the array pass a condition (callback function). It returns true only if every element passes, otherwise false.
It does not change the array.
Example:
const arr = [2, 4, 6];
const allEven = arr.every((num) => num % 2 === 0);
console.log(allEven); // Output: true
Here, all elements of the array are even, so it returns true.
reduceRight()
The reduceRight()
method applies a function against an accumulator and each element of the array (from right to left) to reduce it to a single value.
It works like reduce()
, but starts from the last element and moves to the first.
Example:
const arr = ["a", "b", "c"];
const result = arr.reduceRight((acc, curr) => acc + curr, "");
console.log(result); // Output: "cba"
Here,
- Starts with
acc = ""
(empty string as the initial value). - Combines elements from right to left:
- "" + "c" = "c"
- "c" + "b" = "cb"
- "cb" + "a" = "cba"
- So the output is "cba".
flatMap()
The flatMap()
method first maps each element using a function, then flattens the result by one level.
It's a combination of map()
and flat()
.
Example:
const arr = [1, 2, 3];
const result = arr.flatMap((x) => [x, x * 2]);
console.log(result); // Output: [1, 2, 2, 4, 3, 6]
Here,
- For each element
x
inarr
, the callback returns[x, x * 2]
. - So:
- 1 becomes
[1, 2]
- 2 becomes
[2, 4]
- 3 becomes
[3, 6]
- 1 becomes
flatMap()
then flattens these arrays into a single array:[1, 2]
becomes 1, 2[2, 4]
becomes 2, 4[3, 6]
becomes 3, 6
- So the output is
[1, 2, 2, 4, 3, 6]
.
Summary
JavaScript offers many ways to loop through and process arrays, each suited for different needs:
for
loop: Traditional and flexible, good for simple iteration with control over index.forEach()
: Runs a function on each element, ideal for side effects, no return value.map()
: Transforms each element into a new array.filter()
: Creates a new array with elements that pass a condition.reduce()
: Reduces the array to a single value by accumulating results.for...of
: Simple syntax to iterate over values directly.for...in
: Iterates over keys (indexes), not recommended for arrays. Because it iterates over all enumerable properties, not just array elements.entries(), keys(), values()
: Provide iterable access to indexes and/or values.find(), findIndex()
: Find elements or their indexes by condition.some(), every()
: Check if any or all elements meet a condition.reduceRight(), flatMap()
: Variations of reduce and map with special behaviors.