please give me examples of javascript loop: "for..of"
- User
please give me examples of javascript loop: "for..of"
Assistant
A great choice!
for...ofis a fantastic loop in JavaScript, introduced in ECMAScript 2015 (ES6). It's super useful for iterating over iterable objects, such as arrays, strings, maps, sets, and more. Here are some examples to get you started:Example 1: Looping over an Array
const colors = ['red', 'green', 'blue']; for (const color of colors) { console.log(color); } // Output: // red // green // blueIn this example,
colortakes the value of each element in thecolorsarray on each iteration.Example 2: Looping over a String
const name = 'John'; for (const char of name) { console.log(char); } // Output: // J // o // h // nHere,
charrepresents each character of thenamestring.Example 3: Looping over a Set
const uniqueNumbers = new Set([1, 2, 3, 2, 1]); for (const num of uniqueNumbers) { console.log(num); } // Output: // 1 // 2 // 3Notice that duplicates are automatically ignored, as Sets only store unique values.
Example 4: Looping over a Map
const person = new Map([ ['name', 'Jane'], ['age', 30], ['city', 'Paris'] ]); for (const [key, value] of person) { console.log(`${key}: ${value}`); } // Output: // name: Jane // age: 30 // city: ParisIn this case, we use destructuring (
[key, value]) to access both the key and value of each entry in thepersonmap.Example 5: Looping over a NodeList (DOM elements)
<!-- HTML --> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul>// JavaScript const listItems = document.querySelectorAll('li'); for (const item of listItems) { console.log(item.textContent); } // Output: // Item 1 // Item 2 // Item 3querySelectorAllreturns a NodeList, which is iterable, so we can loop over it withfor...of.Example 6: Looping over a Generator
function* fibonacci() { let a = 0, b = 1; while (true) { yield a; [a, b] = [b, a + b]; } } const fibGen = fibonacci(); for (const num of fibGen) { console.log(num); if (num > 10) break; // stop the infinite generator } // Output: // 0 // 1 // 1 // 2 // 3 // 5 // 8 // 13Here, we create a generator function
fibonacciand loop over its values usingfor...of. We manually stop the loop when the value exceeds 10.Key benefits of
for...of:- No need to manage indices (unlike
for (let i = 0...) - Works with any iterable object, not just arrays
- Cleaner syntax, easier to read and write
- Less prone to errors, as you don't have to worry about indexing or
lengthproperties
What you can't do with
for...of:- Access the index of the current element (use
Array.prototype.entries()orArray.prototype.keys()for that) - Iterate over plain objects (use
for...inorObject.keys()/Object.values()/Object.entries()instead)
Now, go ahead and
for...ofyour way to cleaner, more readable JavaScript code!Hope these examples helped! Do you have any specific questions about
for...of?- No need to manage indices (unlike
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.