JavaScript Iterables
In JavaScript, iterables are objects that implement the Symbol.iterator method, which returns an iterator.
Iterators are objects with a next() method, which returns the next value in the sequence along with a boolean indicating whether the iteration has ended.
Iterables and iterators are fundamental concepts used in JavaScript for looping over data structures like arrays, sets, maps, strings, etc., using constructs like for...of loops and the spread operator (...).
Example
const myIterable = { [Symbol.iterator]: function* () { yield 1; yield 2; yield 3; } }; // Using for...of loop to iterate over the iterable for (let value of myIterable) { console.log(value); // Output: 1, 2, 3 }
Iterating Over an Array
an example of iterating over an array in JavaScript using a for...of loop:
Example
const myArray = [1, 2, 3, 4, 5]; for (let element of myArray) { console.log(element); }
Iterating Over a String
You can iterate over a string in JavaScript using a for...of loop as well. Here's an example:
Sytax
const myString = 'Hello, world!'; for (let char of myString) { console.log(char); }
Iterating Over a Map
Iterating over a Map in JavaScript can be done using a for...of loop or by utilizing the Map's forEach method.
Example
// Creating a Map const myMap = new Map(); myMap.set('a', 1); myMap.set('b', 2); myMap.set('c', 3); // Iterating over the Map using a for...of loop console.log("Iterating over the Map using for...of loop:"); for (let [key, value] of myMap) { console.log(key + ' = ' + value); } // Iterating over the Map using forEach method console.log("\nIterating over the Map using forEach method:"); myMap.forEach((value, key) => { console.log(key + ' = ' + value); });
Iterating Over a Set
Iterating over a Set in JavaScript can also be done using a for...of loop or by utilizing the Set's forEach method.
Iterating Over a String
// Creating a Set const mySet = new Set(); mySet.add(1); mySet.add(2); mySet.add(3); // Iterating over the Set using a for...of loop console.log("Iterating over the Set using for...of loop:"); for (let value of mySet) { console.log(value); } // Iterating over the Set using forEach method console.log("\nIterating over the Set using forEach method:"); mySet.forEach(value => { console.log(value); });