Last active
May 8, 2024 13:40
-
-
Save kevinhooke/821b3f21518b43fcddea023d7eea1da9 to your computer and use it in GitHub Desktop.
Javascript iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Standard loops: | |
//standrd for loop | |
for(let i=0; i<10; i++) { } | |
//for in: loop over properties of an object | |
//loop each property of obj | |
for(let prop in obj) { } | |
//for of: loop over iterable objects such as elements in an array | |
let a = [1,2,3]; | |
//loops over each element in the array | |
for (let element of a) { } | |
// .forEach() | |
[1, 2, 3].forEach( i => { doSomethingWith } ); | |
Iterators: | |
- anything that implements Iterator protocol by implementing next() that returns a value and a done property | |
//Get an iterator from Iterable objects, like Map and Set | |
let map = new Map(); | |
let mapIter = map[Symbol.Iterator](); | |
let i = mapIter.next(); | |
console.log(i.value + " : " + i.done); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment