Exploring JavaScript Iteration: for...of, and for...in Loops, Strings, and Maps

Exploring JavaScript Iteration: for...of, and for...in Loops, Strings, and Maps

In this blog post, we'll explore the for...of loop in JavaScript, its application on arrays and strings, and how to iterate over Maps. We'll also touch on why the for...of loop doesn't work directly on objects and provides alternative methods for iterating over object properties.

The for...of Loop

The for...of loop is a modern JavaScript construct that allows you to iterate over iterable objects such as arrays, strings, and maps. Let's see some examples to understand its usage better.

Iterating Over Arrays

Arrays are a common data structure, and iterating over them is a frequent task. Here’s how you can use the for...of loop with arrays:

const arr = [1, 2, 3, 4, 5];
for (const num of arr) {
    console.log(num);
}
//output:
1
2
3
4
5

In this example, the for...of loop iterates over each element in the array arr, printing each number to the console.

Iterating Over Strings

The for...of loop can also be used to iterate over strings, allowing you to process each character individually:

const greetings = "Hello World";
for (const greet of greetings) {
    if (greet == " ") {
        console.log("space detected");
        continue;
    }
    console.log(greet);
}
H
e
l
l
o
space detected
W
o
r
l
d

Here, we iterate over each character in the string greetings. If a space is detected, a message is logged, and the loop continues to the next character.

Working With Maps

Maps are a type of object in JavaScript that hold key-value pairs and maintain the insertion order of keys. Here's how you can create and iterate over a Map:

// Map is an object that holds key value pairs and remember the orignal insertion of the keys (i.e remember the order in which key value pair was inserted)
// It is unique which means there is no duplicate value inside a map
const map = new Map();
map.set("IN", "India");
map.set("USA", "United States of America");
map.set("FR", "France");
map.set("IN", "India"); // Duplicate keys are ignored

console.log(map);

for (const key of map) {
    console.log(key); //it will provide us array of key value pair, each key value pair will make a separate array
}
//output of console.log(map);
Map(3) {
  'IN' => 'India',
  'USA' => 'United States of America',
  'FR' => 'France'
}

//output of console.log(key);
[ 'IN', 'India' ]
[ 'USA', 'United States of America' ]
[ 'FR', 'France' ]

To restructure this array, you can use this syntax to print the key-value pair inside the map:

const map = new Map();
map.set("IN", "India");
map.set("USA", "United States of America");
map.set("FR", "France");
map.set("IN", "India"); // Duplicate keys are ignored

// to destructure that array, we can use this syntax
for (const [key, value] of map) {
    console.log(key, ":-", value)
}
//outputs:
IN :- India
USA :- United States of America
FR :- France

In this example, we create a Map with country codes as keys and country names as values. The for...of loop iterates over the map, destructuring each key-value pair and logging them to the console.

Iterating over objects

Unlike arrays, strings, and maps, plain objects are not iterable by default. Attempting to use the for...of loop on an object will result in an error:

const myObject = {
    game1: "NFS",
    game2: "Spiderman"
};

// This will throw an error
for (const [key, value] of myObject) {
    console.log(key, ":-", value); //will throw error that myObject is not iterable as "for of" loop is not working here, but there are different methods 
}

Therefore "for in" loop is used to iterate over object

Using for..in Loop for Objects

The for..in loop in JavaScript is specifically designed to iterate over the properties of an object. It provides access to each enumerable property name (or key) of an object.

const myObject = {
    js: "javascript",
    cpp: "c++",
    rb: "ruby",
    swift: "swift by apple"
};

for (const key in myObject) {
    console.log(key); // Outputs each property name (key)
    console.log(myObject[key]); // Outputs each property value
    console.log(`${key} is a shortcut for ${myObject[key]}`);
}
//output of console.log(key)
js
cpp
rb
swift

//output of console.log(myObject[key])
javascript
c++
ruby
swift by apple

//output of console.log(`${key} is a shortcut for ${myObject[key]}`)
js is shortcut for javascript
cpp is shortcut for c++
rb is shortcut for ruby
swift is shortcut for swift by apple

Applying for..in Loop on Arrays

While for..in is primarily intended for objects, it can also iterate over the indices of an array. However, it's important to note that it's less commonly used for this purpose due to its behavior with array indices.

const programming = ["js", "rb", "py", "java", "cpp"];
for (const key in programming) {
    console.log(key);
    console.log(programming[key]); // Outputs each element in the array
}
//output for console.log(key);
0
1
2
3
4

//output of console.log(programming[key]);
js
rb
py
java
cpp

Iterating through Map Objects using the "for in" loop

Maps are key-value pairs where keys can be of any type, and values can also be any type. They differ from regular objects primarily in their properties and methods, including how they are iterated.

const map = new Map();
map.set("IN", "India");
map.set("USA", "United States of America");
map.set("FR", "France");
map.set("IN", "India"); // Adding duplicate key, which won't be added

// Attempting to use for..in loop on Map (incorrect usage)
for (const key in map) {
    console.log(key); 
    // This will not work as Map objects are not iterable in this manner
}

Why for..in Doesn't Work with Maps

Maps are not designed to be iterated over using the for..in loop. Unlike regular objects, which use enumerable properties, maps are iterable objects with specific methods for iteration:

  • for..in: Iterates over enumerable properties of an object, including inherited ones. It is not suitable for iterating over Map objects because Map is not considered iterable in this manner.

  • for..of (Alternative): The correct way to iterate through a Map is using the for..of loop, which is designed for iterable objects like arrays, strings, and Map objects.

for Map                                                     for Objects
for-of loop works                                           for-of doesn't work
for-in loop doesn't work                                    for-in works

Conclusion

When working with Map objects in JavaScript, it's crucial to use the correct iteration method to avoid errors and ensure efficient code execution. While for..in is useful for iterating over object properties, it is not suitable for Map objects. Instead, leverage the for..of loop with the appropriate Map methods for seamless iteration through key-value pairs.