Map Mutation During Iteration Semantics

Map iteration is live: entries appended mid-loop get visited, entries deleted before being reached are skipped, and re-sets keep their position.

JavascriptData Integrity

Code

javascriptsnippet
21 lines
// Map mutation during iteration is live: entries added while iterating WILL
// be visited, entries deleted before being reached WILL be skipped.
const queue = new Map([["email", 1], ["sms", 1]]);

for (const [channel, count] of queue) {
  console.log("visiting:", channel, "weight", count);
  if (channel === "email") {
    queue.set("push", 1); // appended after "sms", so it is still reached
  }
  if (channel === "sms") {
    queue.delete("push"); // never visited, so deleting it works
  }
}
console.log("remaining keys:", [...queue.keys()]);

// Re-setting an existing key keeps its original insertion position
const order = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (const [key] of order) {
  if (key === "a") order.set("b", 99);
}
console.log("order preserved:", [...order.keys()], "| b value updated:", order.get("b"));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

visiting: email weight 1
visiting: sms weight 1
remaining keys: [ 'email', 'sms' ]
order preserved: [ 'a', 'b', 'c' ] | b value updated: 99

How the file behaves

The core work runs in nested loops — outer for (const [channel, count] of queue), inner for (const [key] of order).

Top-level bindings queue, order hold the demo state — nothing sits inside a function scope.

Watch out for

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Using it

The run emits 3 labeled sections — visiting:, remaining keys:, order preserved: — one per step.

Key statements

const order = new Map([["a", 1], ["b", 2], ["c", 3]]);
const queue = new Map([["email", 1], ["sms", 1]]);

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `queue`, `order`.