JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Array Iteration


📘 JavaScript Array Iteration – Looping Through Array Elements

Array iteration refers to looping through each element of an array and performing an action like logging, modifying, or calculating values.

JavaScript provides multiple ways to iterate through arrays:


🔹 1. for Loop (Traditional)

let fruits = ["Apple", "Banana", "Mango"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

✅ Best for flexibility and index-based logic.


🔹 2. forEach() Method

fruits.forEach(function(fruit) {
  console.log(fruit);
});

✅ Runs a function for each element — doesn't return a new array.


🔹 3. map() Method

let lengths = fruits.map(fruit => fruit.length);
// [5, 6, 5]

✅ Transforms elements and returns a new array.


🔹 4. for...of Loop

for (let fruit of fruits) {
  console.log(fruit);
}

✅ Simple and clean for reading array values directly.


🔹 5. filter() Method

let longNames = fruits.filter(fruit => fruit.length > 5);
// ["Banana"]

✅ Returns a new array based on a condition.


🔹 6. reduce() Method

let sum = [1, 2, 3].reduce((total, num) => total + num, 0);
// 6

✅ Reduces the array to a single value.


🔹 7. for...in Loop (less preferred for arrays)

for (let index in fruits) {
  console.log(index + ": " + fruits[index]);
}

⚠️ Used for objects — may include unexpected keys in arrays.


Practice Questions

Q1. How do you print each element of an array using a traditional for loop?

Q2. Which method is used to execute a function on every element without returning a new array?

Q3. How do you create a new array where each value is doubled?

Q4. Which loop allows you to access each value directly without an index?

Q5. What method returns a new array of elements that pass a test condition?

Q6. How do you find the total of an array like [5, 10, 15] using one function?

Q7. How is the for...in loop different from for...of when used on arrays?

Q8. What method would you use to count how many items in an array are longer than 5 characters?

Q9. Which array method does not mutate the original array but returns a new one?

Q10. How do you iterate and log both index and value using forEach()?


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top