JavaScript provides several methods for iterating over an array. In this section, we will discuss some of the most commonly used array iteration methods in JavaScript.
- forEach()
The forEach() method executes a provided function once for each array element.
Syntax
array.forEach(function(currentValue, index, arr), thisValue)
Example
let fruits = ["apple", "banana", "mango", "orange"];
fruits.forEach(function(fruit, index) {
console.log(index + 1 + ". " + fruit);
});
Output
1. apple
2. banana
3. mango
4. orange
- map()
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
Syntax
array.map(function(currentValue, index, arr), thisValue)
Example
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(function(num) {
return num * num;
});
console.log(squares); // [1, 4, 9, 16, 25]
- filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Syntax
array.filter(function(currentValue, index, arr), thisValue)
Example
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evenNumbers); // [2, 4]
- reduce()
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
Syntax
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Example
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function(total, num) {
return total + num;
}, 0);
console.log(sum); // 15
- every()
The every() method tests whether all elements in the array pass the test implemented by the provided function.
Syntax:
array.every(function(currentValue, index, arr), thisValue)
Example
let numbers = [1, 2, 3, 4, 5];
let isPositive = numbers.every(function(num) {
return num > 0;
});
console.log(isPositive); // true
- some()
The some() method tests whether at least one element in the array passes the test implemented by the provided function.
Syntax
array.some(function(currentValue, index, arr), thisValue)
Example
let numbers = [1, 2, 3, 4, 5];
let hasNegative = numbers.some(function(num) {
return num < 0;
});
console.log(hasNegative); // false
Understanding array iteration methods in JavaScript is crucial for any JavaScript developer. These methods make it easy to perform common operations on arrays and are essential for writing efficient and concise code.