JavaScript .keys()

ArieGonzAguer's avatar
Published Aug 5, 2025
Contribute to Docs

The .keys() method returns a new array iterator object containing the keys (indices) for each index in the array.

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours

Syntax

array.keys();

Parameters:

  • This method does not take any parameters.

Return value:

  • A new array iterator object containing the keys (indices) of the array.

Example 1: Using .keys() to Get Array Indices

In this example, the .keys() method creates an iterator over the indices of the array:

const cats = ['Sundae', 'Gandalf', 'Campanita'];
const catsIterator = cats.keys();
for (const cat of catsIterator) {
console.log(cat);
}

Here is the output:

0
1
2

Example 2: Converting the .keys() Iterator to an Array

In this example, the spread operator (...) with .keys() is used to convert the index iterator into a full array of indices:

const colors = ['red', 'black', 'white'];
const indices = [...colors.keys()];
console.log('Array indices: ', indices);
console.log('First index: ', indices[0]);

Here is the output:

Array indices: [0, 1, 2]
First index: 0

Codebyte Example: Using .keys() with Sparse Arrays

In this codebyte example, .keys() is used on a sparse array. Even though some elements are missing, .keys() still returns all valid indices:

Code
Output

All contributors

Contribute to Docs

Learn JavaScript on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours