JavaScript Array Iteration
Array iteration methods enable you to process each element in a systematic way. Whether you need to apply a function to each element, transform data, or filter values, iteration methods simplify these tasks.
Key Topics
forEach()
forEach()
executes a provided function once for each array element.
let nums = [1, 2, 3];
nums.forEach(num => console.log(num * 2));
Output
> 2
> 4
> 6
Explanation: Each number in the array is doubled and logged to the console.
map()
map()
creates a new array by applying a function to each element of the original array.
let doubled = nums.map(num => num * 2);
console.log(doubled);
Output
> [2, 4, 6]
Explanation: map()
returns a new array containing each element of nums
multiplied by 2, without changing the original array.
filter()
filter()
returns a new array containing elements that pass a given test (condition).
let filtered = nums.filter(num => num > 1);
console.log(filtered);
Output
> [2, 3]
Explanation: filter()
returns an array with only the elements greater than 1, resulting in [2, 3].
JavaScript Usage in DOM
This DOM-based example demonstrates using iteration methods to transform and display data on the webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Iteration in DOM</title>
</head>
<body>
<h1>Array Iteration Demo</h1>
<button onclick="showResults()">Show Results</button>
<div id="output"></div>
<script>
function showResults() {
let numbers = [1, 2, 3];
let multiplied = numbers.map(n => n * 3);
document.getElementById("output").textContent = multiplied.join(", ");
}
</script>
</body>
</html>
Key Takeaways
- forEach(): Executes a function for each element.
- map(): Creates a new array with transformed elements.
- filter(): Extracts elements that meet a condition.
- DOM Integration: Use iteration methods to manipulate and display data dynamically.