You are currently viewing JavaScript Cheat Sheet 10.23 : JavaScript Array Iteration

JavaScript Cheat Sheet 10.23 : JavaScript Array Iteration

JavaScript Array Iteration

Introduction

Welcome to the exciting world of programming with JavaScript! In this tutorial, we will delve into the basics of JavaScript array iteration. Arrays are fundamental data structures that store collections of values. Iterating over arrays is a common operation in programming, and JavaScript provides powerful tools to perform these tasks efficiently.

Understanding JavaScript Arrays

Arrays in JavaScript are used to store multiple values in a single variable. Each element in an array has a unique index, starting from 0. Let’s create a simple array to use throughout this tutorial:

// Sample array
let fruits = ['apple', 'banana', 'orange', 'grape'];

Iterating through Arrays with for Loop

Code Example:

// Using a for loop for array iteration
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Output:

apple
banana
orange
grape

Step-by-Step Explanation:

  1. Initialization (let i = 0): Start by initializing a variable i to 0, representing the index of the first element in the array.
  2. Condition (i < fruits.length): Set the condition to continue the loop as long as i is less than the length of the array (fruits.length).
  3. Increment (i++): After each iteration, increment the value of i by 1 to move to the next array element.
  4. Logging (console.log(fruits[i])): Print the current array element using console.log().

The forEach Method

JavaScript provides a convenient forEach method for array iteration.

Code Example:

// Using forEach for array iteration
fruits.forEach(function(fruit) {
  console.log(fruit);
});

Output:

apple
banana
orange
grape

Step-by-Step Explanation:

  1. forEach Method: Call the forEach method on the array fruits.
  2. Callback Function: Pass a callback function as an argument to forEach. This function will be executed for each element in the array.
  3. Logging (console.log(fruit)): The callback function takes an argument (here, named fruit), representing the current array element. Use console.log() to print each element.

Filtering Arrays with filter Method

The filter method creates a new array with elements that pass a certain condition.

Code Example:

// Using filter to select fruits with more than five letters
let filteredFruits = fruits.filter(function(fruit) {
  return fruit.length > 5;
});

console.log(filteredFruits);

Output:

[ 'banana', 'orange' ]

Step-by-Step Explanation:

  1. filter Method: Call the filter method on the array fruits.
  2. Callback Function (function(fruit) { return fruit.length > 5; }): The callback function returns true for elements that satisfy the condition (here, fruits with more than five letters).
  3. Filtered Array (console.log(filteredFruits)): Print the new array containing only the filtered elements.

Mapping Arrays with map Method

The map method creates a new array by applying a function to each element.

Code Example:

// Using map to create an array of uppercase fruits
let uppercaseFruits = fruits.map(function(fruit) {
  return fruit.toUpperCase();
});

console.log(uppercaseFruits);

Output:

[ 'APPLE', 'BANANA', 'ORANGE', 'GRAPE' ]

Step-by-Step Explanation:

  1. map Method: Call the map method on the array fruits.
  2. Callback Function (function(fruit) { return fruit.toUpperCase(); }): The callback function transforms each element (here, converts each fruit to uppercase using toUpperCase()).
  3. Mapped Array (console.log(uppercaseFruits)): Print the new array containing the transformed elements.

Summing Values with reduce Method

The reduce method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Code Example:

// Using reduce to calculate the total length of all fruits
let totalLength = fruits.reduce(function(acc, fruit) {
  return acc + fruit.length;
}, 0);

console.log(totalLength);

Output:

22

Step-by-Step Explanation:

  1. reduce Method: Call the reduce method on the array fruits.
  2. Callback Function (function(acc, fruit) { return acc + fruit.length; }): The callback function takes two arguments – the accumulator (acc) and the current array element (fruit). It adds the length of each fruit to the accumulator.
  3. Initial Value (0): Provide an initial value for the accumulator as the second argument to reduce (here, 0).
  4. Result (console.log(totalLength)): Print the final result, which is the total length of all fruits.

Conclusion

Congratulations! You’ve now learned the basics of JavaScript array iteration using for loops and array methods like forEach, filter, map, and reduce. Practice these concepts to strengthen your understanding, and feel free to explore more advanced array manipulation techniques as you progress in your programming journey.

Happy coding!

Leave a Reply