JavaScript Map Iteration: Entries, Keys and Values
Quick answer
Map iteration exposes ordered key–value entries, keys or values. Unlike object enumeration, keys are not converted to property-name strings.
How it works
entries() and the default iterator yield pairs; keys() and values() yield one component. forEach(callback) calls the callback with value, key and map. Updating an existing key preserves its position, while delete and reinsert moves it to the end. Iterators are live rather than frozen snapshots; use a copied array when the traversal must not reflect later edits.
const m = new Map([["a",1],["b",2]]); m.set("a",9); console.log(JSON.stringify([...m]));Expected output in Node.js:
[["a",9],["b",2]]Updating a key preserves insertion position.
const m = new Map([["a",2],["b",4]]); const out=[]; m.forEach((v,k)=>out.push(k+v)); console.log(out.join(","));Expected output in Node.js:
a2,b4forEach supplies value before key.
Common mistakes
Do not confuse the forEach argument order with [key, value]. Avoid repeatedly inserting during a live traversal unless you have a clear termination condition.
Practice
Transform a list of key/quantity pairs into an ordered list of final entries, with the last quantity winning.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Map Iteration: Entries, Keys and Values — Knowledge Check
Apply the taught concept and predict the output.
Which Map method produces key–value pair iterators?
What is the first argument of a Map forEach callback?
How can you make a snapshot of Map entry order before edits?
What is the exact console output in JavaScript Map Iteration: Entries, Keys and Values example 1?
const m = new Map([["a",1],["b",2]]); m.set("a",9); console.log(JSON.stringify([...m]));What is the exact console output in JavaScript Map Iteration: Entries, Keys and Values example 2?
const m = new Map([["a",2],["b",4]]); const out=[]; m.forEach((v,k)=>out.push(k+v)); console.log(out.join(","));