Open In App

What is the use of the Map.prototype.keys method in JavaScript Maps ?

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, the Map.prototype.keys method is used to get an iterator object that contains the keys of a Map. The iterator object follows the iterable protocol, allowing you to loop through the keys using methods like next() or using a for...of loop.

Syntax:

myMaps.key();
  • myMap: The Map for which you want to obtain an iterator for its keys.

Example: Below is an example of a key method in a map.

Javascript




let myMap = new Map();
 
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
myMap.set('key3', 'value3');
 
// Get an iterator for the keys of the Map
let keysIterator = myMap.keys();
 
// Use the iterator to loop through the keys
let nextKey = keysIterator.next();
while (!nextKey.done) {
  console.log(nextKey.value);
  nextKey = keysIterator.next();
}


Output

key1
key2
key3


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads