JS Built-ins
← Array120 / 226
ArrayArray.prototype.keysintermediate

Array.prototype.keys() β€” iterate with for…of

πŸ“– Usage Example
const arr = ['red', 'green', 'blue']
for (const i of arr.keys()) {
  console.log(i)  // 0, 1, 2
}

Use keys() with for-of to iterate over only the indices of an array.

Array.prototype.keys() β€” for…of loop

Because keys() returns an iterator, you can consume it directly inside a for…of loop without converting it first. This is useful when you want to build up a result array manually.

Challenge: Implement keysToArray(arr) using a for…of loop over arr.keys() to collect all indices.

keysToArray(['x', 'y', 'z']) // β†’ [0, 1, 2]
keysToArray([])              // β†’ []
πŸ’‘ Hints (2)
  • β€’ `for (const i of arr.keys())` gives you each index as a number.
  • β€’ Push each `i` into the `result` array inside the loop.