JS Data Structures#1: Understanding Iterables and Iteration in JavaScript
Learn what iterables are, how iteration works in JavaScript, and how to use loops to traverse collections of data.
What is Iteration?
Iteration is the process of repeating a block of code to go through each element in a collection (like an array, string, or object). It helps automate repetitive tasks instead of manually accessing each item.
Common Examples of Iteration:
Looping through an array of names to print each one.
Reading characters in a string one by one.
Extracting key-value pairs from an object.
What is an Iterable?
An iterable is any object that can be looped over using a for...of loop or spread operator (...).
Built-in Iterable Objects in JavaScript:
Arrays (
[1, 2, 3])Strings (
"hello")Maps (
new Map([["name", "John"]]))Sets (
new Set([1, 2, 3]))NodeLists (
document.querySelectorAll("div"))
How to Iterate in JavaScript
1. for...of Loop (Best for Arrays, Strings, Maps, Sets)
Loop through each element in an iterable:
console.log("---Iterating array----");
const fruits = ["Apple", "Banana", "Orange"];
for (const fruit of fruits) {
console.log(fruit); // Apple, Banana, Orange
}
console.log("---Iterating string----");
const str = "hello";
for (const char of str) {
console.log(char); // Outputs: h, e, l, l, o
}
console.log("---Iterating map----");
const map = new Map([
["a", 1],
["b", 2],
]); // A collection of key-value pairs that is iterable.
for (const [key, value] of map) {
console.log(`${key}: ${value}`); // Outputs: a: 1, b: 2
}
console.log("---Iterating set----");
const set = new Set([1, 2, 3]); // A collection of unique values that is also iterable.
for (const value of set) {
console.log(value); // Outputs: 1, 2, 3
}
console.log("---Iterating arguments object----");
// The arguments object in functions is also iterable.
function example() {
for (const arg of arguments) {
console.log(arg);
}
}
example(1, 2, 3); // Outputs: 1, 2, 3
console.log("---Iterating nodelist----");
const nodeList = document.querySelectorAll("div"); // Collections of nodes returned by methods like document.querySelectorAll.
for (const node of nodeList) {
console.log(node); // Outputs each <div> element
}
2. forEach() (For Arrays Only)
Loop through each array element:
const numbers = [1, 2, 3];
numbers.forEach(number => {
console.log(number * 2); // 2, 4, 6
});
3. for...in Loop (For Objects)
Loop through keys of an object (not recommended for arrays):
const person = { name: "Alice", age: 25 };
for (const key in person) {
console.log(`${key}: ${person[key]}`); // name: Alice, age: 25
}
4. Spread Operator (...)
Convert an iterable into individual elements:
const word = "Hello";
const letters = [...word]; // ["H", "e", "l", "l", "o"]
Final Thoughts
Use
for...offor arrays, strings, maps, sets.Use
forEach()for simple array looping.Avoid
for...infor arrays; use it for objects instead.The spread operator (
...) makes working with iterables flexible.