CKTIS / JavaScript
Map iterators: next(), value, and done
Step through a Map iterator with `next()` and use `done` to tell a stored `undefined` apart from the end of iteration.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const iterator = map.entries(); // or map.keys(), map.values(), map[Symbol.iterator]()
const { value, done } = iterator.next();Map iterator next/value is a two-part operation: iterator.next() takes one step, and result.value reads the value from that step. next() is a method on the iterator, not on the Map, and returns a result object with value and done. Reading value does not advance the iterator; calling next() again does. Save the result if you need both properties from the same step. Calling a detached next without the correct this throws TypeError.
map.keys() yields keys and map.values() yields stored values. map.entries() and map[Symbol.iterator]() both yield a fresh two-element [key, value] array as result.value on each successful step. All three kinds visit entries in insertion order. Check done, not value: done: false means an item was yielded, even if value is undefined. An exhausted Map iterator returns { value: undefined, done: true }.
A Map iterator is not a snapshot: it can see entries added before exhaustion, but once it returns done: true, it never resumes. Create a new iterator to start over. This is built-in Map behavior in ECMAScript 2024; runtime support varies.
Examples
{
const map = new Map([["a", undefined], ["b", 7]]);
const iterator = map.values();
function logStep({ value, done }) {
console.log(`done=${done}, value=${value}`);
}
logStep(iterator.next());
logStep(iterator.next());
logStep(iterator.next());
map.set("c", 9);
logStep(iterator.next());
console.log(JSON.stringify(map.entries().next().value));
}Result
done=false, value=undefined done=false, value=7 done=true, value=undefined done=true, value=undefined ["a",null]
The first step yields a stored `undefined`; the third signals exhaustion. Adding `"c"` does not revive the iterator. A fresh entries iterator starts at `"a"`; in the last line, `JSON.stringify()` represents the array's `undefined` element as `null` without changing the map.
Related lessons
- JavaScript · Lesson 7 · Advanced · Version: 4
Sources
- ECMAScript 2024 Language Specification — Map Iterator Objects
- ECMAScript Language Specification — Properties of the Map Prototype Object
- ECMAScript Language Specification — Map Iterator Objects
- ECMAScript 2024 Language Specification — GeneratorResume
- ECMAScript 2024 Language Specification — GeneratorValidate