CKTIS / JavaScript
Map.prototype.forEach: callback for every entry
The forEach method calls a callback for every Map entry in insertion order, passing the value, key, and the Map itself.
Version: ECMAScript 2015 onward; example target: Node.js 24.22.2
Syntax
map.forEach(callbackFn[, thisArg])map.forEach(callbackFn, thisArg?) invokes callbackFn(value, key, map) for every non-deleted entry and returns undefined. Its argument order starts with the value, unlike the pair from entries(). Optional thisArg becomes callback this under ordinary call rules; an arrow function ignores it through lexical this.
Traversal is live, not a snapshot. An entry deleted before its visit is skipped; one deleted and re-added can be visited at its new position, and an entry added before completion can also be visited. Updating a not-yet-visited key passes its new value.
A non-callable callback or receiver without Map internal data throws TypeError; a callback exception stops traversal. There is no built-in break, and returned promises are not awaited. The method has been standard since ECMAScript 2015; use for...of for break, continue, or sequential await.
Examples
const map = new Map([["a", 1], ["b", 2]]);
const seen = [];
const result = map.forEach(function (value, key, original) {
seen.push(this.prefix + key + ":" + value);
if (key === "a") {
original.delete("b");
original.set("c", 3);
}
}, { prefix: "#" });
console.log(seen.join(","));
console.log(result === undefined);
console.log([...map].map(([key, value]) => key + ":" + value).join(","));
try {
map.forEach(null);
} catch (error) {
console.log(error instanceof TypeError);
}Result
#a:1,#c:3 true a:1,c:3 true