Array.entries Walks Index And Value Together

Array.prototype.entries yields index-and-value pairs for for-of, .keys and .values give each half alone, and sparse arrays report holes as undefined.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
const stages = ['build', 'test', 'deploy'];

// for-of over .entries() yields [index, value] pairs: enumeration without a
// manual counter variable to keep in sync
for (const [index, stage] of stages.entries()) {
  console.log(index + ': ' + stage);
}

// .keys() yields just the indices, .values() just the elements
console.log([...stages.keys()].join(','));
console.log([...stages.values()].length === stages.length);

// entries() returns an iterator, so each pass consumes from its own cursor
const it = stages.entries();
console.log(it.next().value);
console.log(it.next().done);

// Sparse arrays still report real indices; holes come back as undefined
const sparse = ['a', , 'c'];
console.log(JSON.stringify([...sparse.entries()]));

Output

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

0: build
1: test
2: deploy
0,1,2
true
[ 0, 'build' ]
false
[[0,"a"],[1,null],[2,"c"]]

How it works

The file repeats itself only inside for (const [index, stage] of stages.entries()).

Module-level bindings hold the data — stages, it, sparse — with no function scope in between.

What to watch for

  • The import surface (if any) is all standard library, all versioned with the language itself.

Key statements

const stages = ['build', 'test', 'deploy'];
const it = stages.entries();
const sparse = ['a', , 'c'];

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `stages`, `it`, `sparse`.