How to iterate over an array with a classic for-loop?
let arr = ["a", "b", "c"];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
How to iterate over an array with an "enhanced" for-loop?
let arr = ["a", "b", "c"];
for (let elem of arr) {
console.log(elem);
}
How to iterate over an array by passing a function for element processing?
let arr = ["a", "b", "c"];
arr.forEach((value, index) => console.log(`${index}: ${value}`));
How to create an iterator over the values from 3 to 5?
// this is a generator function;
// note the asterisk "*" after the "function" keyword:
function* createIterator() {
yield 3;
yield 4;
yield 5;
/* alternative #1:
for (let i = 3; i <= 5; i++) {
yield i;
}
*/
/* alternative #2:
// note the asterisk here, making yield iterate over its operand:
yield* [3, 4, 5];
*/
}
let iter = createIterator();
for (let elem of iter) {
console.log(elem);
// output:
// 3
// 4
// 5
}