JS Array Iteration 🎯

beginner
7 min

JS Array Iteration 🎯

Welcome to our deep dive into JavaScript (JS) Array Iteration! In this lesson, we'll explore how to traverse, manipulate, and understand arrays, a fundamental data structure in JavaScript. By the end, you'll be able to confidently work with arrays in your projects.

What is an Array? 📝

An array is a collection of values, all of the same data type, stored in contiguous memory locations, and accessed using an index. In JavaScript, arrays are created using square brackets ([]).

javascript
const myArray = ['apple', 'banana', 'cherry']; // This is an example of an array

Array Iteration Methods 💡

Iterating through an array means visiting each element in the array and performing some operation on it. JavaScript provides several built-in methods for iterating arrays. Let's explore some of them:

1. for loop

The for loop is a traditional way to traverse an array.

javascript
const myArray = ['apple', 'banana', 'cherry']; for (let i = 0; i < myArray.length; i++) { console.log(myArray[i]); // Logs each element of the array }

2. for...of loop

The for...of loop is a newer and more elegant way to iterate arrays in JavaScript.

javascript
const myArray = ['apple', 'banana', 'cherry']; for (const fruit of myArray) { console.log(fruit); // Logs each element of the array }

3. map()

The map() method creates a new array with the results of calling a provided function on every element in the original array.

javascript
const myArray = ['apple', 'banana', 'cherry']; const newArray = myArray.map((fruit) => fruit.toUpperCase()); // Converts all elements to uppercase console.log(newArray); // Logs: ['APPLE', 'BANANA', 'CHERRY']

4. filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

javascript
const myArray = ['apple', 'banana', 'cherry', 'orange']; const fruits = myArray.filter((fruit) => fruit !== 'orange'); // Filters out 'orange' console.log(fruits); // Logs: ['apple', 'banana', 'cherry']

5. reduce()

The reduce() method applies a function against an accumulator and each element in the array, resulting in a single output value.

javascript
const myArray = ['apple', 'banana', 'cherry']; const fruitList = myArray.reduce((accumulator, fruit) => { accumulator += `${fruit}, `; // Concatenates each fruit with a comma and a space return accumulator; }, ''); // Initial value of the accumulator console.log(fruitList); // Logs: 'apple, banana, cherry, '

Quiz 💡

Quick Quiz
Question 1 of 1

Which loop is considered a more modern and elegant way to iterate arrays in JavaScript?

By now, you should have a solid understanding of array iteration in JavaScript. Remember, practice makes perfect, so keep coding and experimenting with these methods! Happy coding! 🚀