Map Preserves Insertion Order For Iteration

Map iterates in first-insertion order: re-setting a key keeps its slot, delete plus re-insert moves it to the end, and integer keys stay put unlike object keys.

JavascriptData Integrity

Code

javascriptsnippet
28 lines
// Map iterates in first-insertion order: keys/values/entries/for..of all follow it
const timeline = new Map();
timeline.set('deploy', '10:00');
timeline.set('test', '10:05');
timeline.set('release', '10:20');
console.log('first pass:', [...timeline.keys()].join(' -> '));

// set on an existing key updates the value but keeps its position
timeline.set('test', '10:06');
console.log('after update:', [...timeline.keys()].join(' -> '));

// delete then set again: the key moves to the end - order reflects the latest insertion
timeline.delete('deploy');
timeline.set('deploy', '11:00');
console.log('after reinsert:', [...timeline.keys()].join(' -> '));

// Contrast: objects reorder integer-like keys ascending by value first, Map always keeps insertion order
const obj = {};
obj[3] = 'c';
obj[1] = 'a';
obj[2] = 'b';
console.log('object int keys:', Object.keys(obj).join(','));
const numbered = new Map([
  [3, 'c'],
  [1, 'a'],
  [2, 'b'],
]);
console.log('map int keys    :', [...numbered.keys()].join(','));

Output

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

first pass: deploy -> test -> release
after update: deploy -> test -> release
after reinsert: test -> release -> deploy
object int keys: 1,2,3
map int keys    : 3,1,2

Inside the snippet

Top-level bindings timeline, obj, numbered hold the demo state — nothing sits inside a function scope.

Using it

The demo output is labeled (first pass:, after update:, after reinsert:), so every printed line maps back to its originating operation.

Key statements

const timeline = new Map();
const numbered = new Map([
  [3, 'c'],
  [1, 'a'],
  [2, 'b'],
]);

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `timeline`, `obj`, `numbered`.