JavaScript .keys()
The .keys() method returns a new map iterator object containing the keys of each element in the map, respecting the insertion order. This method enables explicit iteration using a for...of loop or the iterator’s .next() method.
Note: The iterable returned by
.keys()is not reusable. Once it has been fully consumed (i.e., all elements have been iterated over), it becomes exhausted. To iterate again, a new iterator must be created by calling.keys()again on the map.
Syntax
map.keys();
Parameters:
The .keys() method does not take any parameters.
Return value:
Returns a new map iterator object containing the keys of each element in the map, in order.
Example 1: Printing Each Key
This example uses a for...of loop to iterate over the iterable object returned by .keys() and prints the keys of the ratings map:
const ratings = new Map();ratings.set(1, 'Bad');ratings.set(5, 'Medium');ratings.set(10, 'Excellent');const iterator = ratings.keys();for (const key of iterator) {console.log(key);}
The code will produce this output:
1510
Example 2: Getting the Values
In this example, the keys are saved in the numsKeys array, and the map’s .get() method is used to retrieve and print each value:
const nums = new Map([[2, 'Two'],[4, 'Four'],[6, 'Six'],[8, 'Eight'],]);const numsKeys = Array.from(nums.keys());numsKeys.forEach((key) => console.log(nums.get(key)));
The code will produce this output:
TwoFourSixEight
Codebyte Example
This example uses the .next() method to manually iterate through the keys and print them to the console:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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