JavaScript Loops - Looping Through Arrays


Loops are a fundamental part of programming that allow you to execute a block of code repeatedly. In this guide, we'll explore how to use loops to iterate through arrays in JavaScript and provide examples to illustrate their usage.


Creating Arrays


To work with loops, you first need an array. Here's an example of creating an array:


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

For Loop


The for loop is commonly used to iterate through array elements:


const fruits = ["apple", "banana", "cherry", "date"];
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", "date"];
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", "date"];
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 squaredNumbers = numbers.map(function(number) {
return number * number;
});
console.log(squaredNumbers);

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


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


Happy coding!