JavaScript Arrays - Iterating Through Elements


Arrays are a fundamental data structure in JavaScript that allow you to store and manipulate collections of data. In this guide, we'll explore how to iterate through the elements of an array using various methods, and provide examples to illustrate their usage.


Creating Arrays


To create an array, use square brackets and add elements separated by commas:


const fruits = ["apple", "banana", "cherry"];

For Loop


You can use a for loop to iterate through the elements of an array:


const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

For...of Loop


The for...of loop is a more concise way to iterate through array elements:


const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}

Array.forEach()


The forEach() method is an array method that allows you to iterate through array elements and perform an action on each element:


const fruits = ["apple", "banana", "cherry"];
fruits.forEach(function(fruit) {
console.log(fruit);
});

Array.map()


The map() method creates a new array by applying a function to each element of the original array:


const numbers = [1, 2, 3, 4];
const doubledNumbers = numbers.map(function(number) {
return number * 2;
});
console.log(doubledNumbers);

Array.filter()


The filter() method creates a new array containing elements that meet a specified condition:


const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evenNumbers);

Array.reduce()


The reduce() method can be used to accumulate values in an array into a single result:


const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum);

Conclusion


Iterating through array elements is a common task in JavaScript. By understanding the various methods and loop structures available for array iteration, you can effectively work with collections of data and perform operations on array elements.


Happy coding!