JavaScript offers a variety of ways to iterate over collections, whether arrays, strings, or even custom objects. From traditional while
loops to the elegance of for...of
and the flexibility of Maps, there's a lot to explore. Letβs dive in! π
π Exploring the while
Loop
The while
loop executes a block of code as long as the specified condition is true.
let index = 0;
while (index <= 10) {
console.log(`Value of index is ${index}`);
index = index + 2; // Increment by 2
}
Output:
Value of index is 0
Value of index is 2
...
Value of index is 10
π Iterating Through Arrays with while
let myArray = ['flash', 'batman', 'superman'];
let arr = 0;
while (arr < myArray.length) {
console.log(`Value is ${myArray[arr]}`);
arr = arr + 1;
}
Output:
Value is flash
Value is batman
Value is superman
π The do...while
Loop: Guaranteed First Execution
A do...while
loop ensures the block of code executes at least once, regardless of the condition.
let score = 11;
do {
console.log(`Score is ${score}`);
score++;
} while (score <= 10);
Output:
Score is 11
π― The Elegant for...of
Loop
The for...of
loop is ideal for iterating over iterables like arrays, strings, and even Maps.
Example 1: Iterating Over an Array
const arr = [1, 2, 3, 4, 5];
for (const num of arr) {
console.log(num);
}
Output:
1
2
3
4
5
Example 2: Iterating Over a String
const greetings = "Hello world!";
for (const greet of greetings) {
console.log(`Each char is ${greet}`);
}
Output:
Each char is H
Each char is e
Each char is l
...
Each char is !
π Mastering Maps in JavaScript
Maps provide a flexible and powerful way to store key-value pairs. Unlike objects, they maintain the order of insertion and can have keys of any type.
Creating 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 overwrite existing ones
Iterating Over Maps
for (const [key, value] of map) {
console.log(key, ':-', value);
}
Output:
IN :- India
USA :- United States of America
Fr :- France
π« Can You Use for...of
on Objects?
Plain objects are not iterable by default, so attempting to use for...of
on them results in an error. Instead, you can use Object.entries()
to convert an object into an array of key-value pairs:
const myObject = {
game1: 'NFS',
game2: 'Spiderman'
};
for (const [key, value] of Object.entries(myObject)) {
console.log(key, ':-', value);
}
Output:
game1 :- NFS
game2 :- Spiderman
Key Takeaways
-
while
anddo...while
are useful when youβre unsure how many iterations are required. -
for...of
is the go-to for iterating over iterables like arrays, strings, and Maps. - Maps are excellent for key-value storage with insertion order and flexible key types.
- Use
Object.entries()
to make objects iterable.
By mastering these looping techniques, you can navigate and manipulate data structures like a pro! π
Top comments (0)