These examples demonstrate indexed loops, for...of, forEach, sparse-array behavior, and asynchronous iteration. Each includes a question, complete code, expected output or behavior, and explanation.
How can a loop print each array index and its value?
const tasks = ["Read", "Practice", "Review"];
for (let index = 0; index < tasks.length; index += 1) {
console.log(index + ": " + tasks[index]);
}0: Read
1: Practice
2: Review
An indexed loop exposes the index directly. It is useful when code needs to read or update positions.
How can a loop visit array values without managing an index?
const colors = ["teal", "amber", "violet"];
for (const color of colors) {
console.log(color);
}teal
amber
violet
for...of gives each value in turn. It is usually a clear choice when the index is not needed.
How can a loop skip values and stop early?
const scores = [42, 67, 85, 91, 95];
for (const score of scores) {
if (score < 70) {
continue;
}
console.log(score);
if (score >= 91) {
break;
}
}85
91
continue skips to the next iteration. break ends the loop as soon as the score reaches the stopping condition.
How can a for...of loop process an index and its matching value?
const languages = ["JavaScript", "Python", "Ruby"];
for (const [index, language] of languages.entries()) {
console.log(index + ": " + language);
}0: JavaScript
1: Python
2: Ruby
entries yields index-value pairs. Array destructuring assigns the two parts to index and language.
What does each iterator method provide?
const letters = ["a", "b"];
console.log([...letters.keys()]);
console.log([...letters.values()]);
console.log([...letters.entries()]);[ 0, 1 ]
[ 'a', 'b' ]
[ [ 0, 'a' ], [ 1, 'b' ] ]
keys yields indexes, values yields values, and entries yields pairs. Spread collects the iterator values into arrays for display.
How can a callback use its value, index, and original array?
const colors = ["teal", "amber"];
colors.forEach(function (color, index, originalArray) {
console.log(index + ": " + color + " of " + originalArray.length);
});0: teal of 2
1: amber of 2
The callback receives the current value first, the index second, and the original array third. It can declare only the arguments it needs.
Does a value returned from a forEach callback become the method's result?
const result = [2, 4, 6].forEach(function (number) {
return number * 2;
});
console.log(result);undefined
forEach ignores callback return values and returns undefined. Use map when callback results should form a new array.
Does returning from a callback end the whole forEach iteration?
[1, 2, 3, 4].forEach(function (number) {
if (number === 3) {
return;
}
console.log(number);
});1
2
4
The return exits only the callback invocation for value three. The forEach method continues with the next present element.
What values are visited when an array has a hole?
const values = [];
values.length = 3;
values[1] = "middle";
console.log("forEach:");
values.forEach(function (value, index) {
console.log(index + ": " + value);
});
console.log("for...of:");
for (const value of values) {
console.log(value);
}forEach:
1: middle
for...of:
undefined
middle
undefined
forEach skips missing properties. The array iterator used by for...of yields undefined for each hole position.
How can an indexed loop distinguish a hole from an explicit element?
const values = [];
values.length = 3;
values[1] = undefined;
for (let index = 0; index < values.length; index += 1) {
console.log(index + " present: " + (index in values));
}0 present: false
1 present: true
2 present: false
The indexed loop checks every position in its numeric range. The in operator identifies which positions actually contain properties.
What does for...in include when an array has a custom enumerable property?
const colors = ["teal", "amber"];
colors.note = "palette";
for (const key in colors) {
console.log(key);
}0
1
note
for...in iterates enumerable property keys, including the custom note property. Use for...of to process values.
How can a regular callback use an object as this?
const printer = {
prefix: "Task",
print(value, index) {
console.log(this.prefix + " " + index + ": " + value);
}
};
["Read", "Practice"].forEach(printer.print, printer);Task 0: Read
Task 1: Practice
The second argument to forEach supplies printer as the regular callback's this receiver.
How can an arrow callback call a method through its object?
const printer = {
prefix: "Task",
print(value) {
return this.prefix + ": " + value;
}
};
const tasks = ["Read", "Practice"];
tasks.forEach((task, index) => {
console.log(printer.print(index + 1 + ". " + task));
});Task: 1. Read
Task: 2. Practice
The arrow callback does not need its own this. It calls printer.print as a method, so printer is the method's receiver.
Does forEach wait for asynchronous callback work to finish?
function saveItem(item) {
return Promise.resolve(item);
}
async function demonstrate() {
const completed = [];
[1, 2].forEach(async function (item) {
await saveItem(item);
completed.push(item);
});
console.log("After forEach:", completed.length);
await Promise.resolve();
console.log("After callbacks:", completed.length);
}
demonstrate();After forEach: 0
After callbacks: 2
Each async callback returns a promise, but forEach ignores it and returns immediately. The callbacks resume after their awaits. The extra await lets their continuations finish before the second log.
How can asynchronous operations be processed one at a time in array order?
function saveItem(item) {
return Promise.resolve("saved " + item);
}
async function saveInOrder(items) {
for (const item of items) {
const result = await saveItem(item);
console.log(result);
}
}
saveInOrder(["A", "B", "C"]);saved A
saved B
saved C
The loop waits for each promise before continuing to the next item. This is useful when each operation should complete before the next begins.
How can independent async operations be started and awaited as a group?
function saveItem(item) {
return Promise.resolve("saved " + item);
}
async function saveTogether(items) {
const results = await Promise.all(
items.map(item => saveItem(item))
);
console.log(results);
}
saveTogether(["A", "B", "C"]);[ 'saved A', 'saved B', 'saved C' ]
The map callback creates a promise for each item, and Promise.all waits for all of them. The results array follows the input order. This is appropriate when the operations do not depend on each other.
- Print values with an indexed loop and with for...of.
- Use entries to print positions and values.
- Create an array with a hole and compare forEach, for...of, and an indexed loop.
- Add a custom property and compare for...in with for...of.
- Use forEach with a regular callback and a thisArg.
- Write an async sequential loop with for...of and await.
- Write independent async tasks using Promise.all.
| Previous chapter | Chapter lesson | Chapter Q&A | Next chapter |
|---|---|---|---|
| 45 - Arrays: create, read, and update | Open lesson | Open Q&A | 47 - Transforming arrays: map, filter, reduce, and flat |