-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
Iterating over arrays is a core aspect of JavaScript programming. Arrays often hold multiple values, and performing operations on each element—such as displaying, modifying, or calculating results—requires iteration. JavaScript provides a variety of ways to iterate over arrays, each suited for different scenarios, from simple loops to higher-order functions.
This tutorial covers array iteration techniques, practical examples, best practices, and common mistakes.
Array iteration is essential for:
Processing data from APIs, forms, or user inputs
Applying transformations to each element
Filtering, searching, and aggregating values
Building dynamic lists, tables, and content
Performing calculations on arrays of numbers or objects
Without iteration, working with arrays would be tedious and inefficient.
JavaScript offers several ways to loop through arrays, each with specific advantages.
The classic for loop is straightforward and works in all scenarios:
let fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
This method provides full control over the index and loop behavior.
The for...of loop is modern and readable. It iterates directly over values:
for (let fruit of fruits) {
console.log(fruit);
}
It’s ideal when you don’t need the index.
forEach() is an array method that executes a callback function for each element:
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
Advantages:
Cleaner syntax than for loops
Access to both value and index
Readable and expressive for functional-style programming
Note: forEach() does not return a new array.
map() iterates over an array and returns a new array containing the results of the callback function:
let numbers = [1, 2, 3, 4];
let squares = numbers.map(num => num * num);
console.log(squares); // [1, 4, 9, 16]
map() is ideal for transforming data without mutating the original array.
filter() iterates and creates a new array with elements that pass a condition:
let scores = [45, 78, 90, 60];
let passingScores = scores.filter(score => score >= 60);
console.log(passingScores); // [78, 90, 60]
This is useful for extracting subsets of data.
reduce() iterates over an array and reduces it to a single value, such as a sum or concatenated string:
let total = scores.reduce((sum, score) => sum + score, 0);
console.log(total); // 273
reduce() is powerful for cumulative calculations and aggregations.
Both methods iterate to check conditions:
some() returns true if at least one element satisfies the condition.
every() returns true only if all elements satisfy the condition.
console.log(scores.some(score => score > 90)); // false
console.log(scores.every(score => score >= 45)); // true
for...in iterates over property names. While it can be used for arrays, it’s not recommended because it includes inherited properties and is intended for objects.
for (let index in fruits) {
console.log(fruits[index]);
}
let students = ["Emma", "Lily", "Sophia"];
students.forEach((student, index) => {
console.log(`Student ${index + 1}: ${student}`);
});
let numbers = [2, 4, 6, 8];
let squared = numbers.map(n => n * n);
console.log(squared); // [4, 16, 36, 64]
let ages = [12, 17, 19, 25];
let adults = ages.filter(age => age >= 18);
console.log(adults); // [19, 25]
let prices = [50, 100, 25, 75];
let totalPrice = prices.reduce((sum, price) => sum + price, 0);
console.log(`Total: ${totalPrice}`); // Total: 250
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.some(num => num > 4)); // true
console.log(numbers.every(num => num < 10)); // true
for (let name of students) {
console.log(`Hello, ${name}!`);
}
Using for...in for arrays and unintentionally iterating over inherited properties.
Expecting forEach() to return a new array; it does not.
Forgetting that map(), filter(), and reduce() return new arrays or values and do not modify the original array unless reassigned.
Overusing loops when array methods could provide cleaner, more functional solutions.
Use for...of or forEach() for readable iteration over values.
Use map(), filter(), and reduce() for transformations and calculations.
Avoid for...in for arrays; stick to loops or array methods.
Keep callback functions concise and use arrow functions for readability.
Be mindful of whether the method mutates the original array or returns a new one.
JavaScript provides multiple ways to iterate over arrays, each suited for different purposes. Classic for loops and for...of loops are flexible and simple, while higher-order methods like forEach(), map(), filter(), and reduce() enable functional-style, readable, and efficient processing. Understanding how to iterate effectively allows developers to handle dynamic data, perform calculations, transform arrays, and implement complex logic with clarity and precision. Using the appropriate iteration method ensures code that is maintainable, scalable, and aligned with modern JavaScript practices.
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()?
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 Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
