Map.forEach Passes Value Before Key

Map.forEach passes (value, key) in the opposite order of Object.entries, and JSON.stringify of a Map yields {}, so convert through Object.fromEntries first.

JavascriptData Integrity

Code

javascriptsnippet
19 lines
// Map.forEach passes (value, key, map) — the opposite order of Object.entries.
const scores = new Map([
  ['ada', 91],
  ['lin', 78],
  ['bo', 84],
]);

const lines = [];
scores.forEach((value, key) => lines.push(`${key}=${value}`));
console.log(lines.join(' | '));

// Object.entries on a plain object hands over [key, value] pairs instead.
const plain = { ada: 91, lin: 78 };
console.log(Object.entries(plain).map(([key, value]) => `${key}:${value}`).join(' | '));

// Common trap: JSON.stringify of a Map yields '{}' and Object.entries sees no
// keys, so convert through Object.fromEntries before serializing.
console.log(JSON.stringify(scores), Object.entries(scores).length);
console.log(JSON.stringify(Object.fromEntries(scores)));

Output

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

ada=91 | lin=78 | bo=84
ada:91 | lin:78
{} 0
{"ada":91,"lin":78,"bo":84}

Reading the code — Map.forEach Passes Value Before Key

The file’s state is a handful of top-level bindings: scores, lines, plain.

The top-level object literal pins ada, lin as plain values — no derivation, no imports behind them.

What to watch for

  • Ready as-is on a bare install of the language.

Statements that matter

scores.forEach((value, key) => lines.push(`${key}=${value}`));
const scores = new Map([
  ['ada', 91],
  ['lin', 78],
  ['bo', 84],
]);

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: `scores`, `lines`, `plain`.