JavaScript Map keys()
Syntax & Examples

Map.keys() method

The keys() method of the Map object in JavaScript returns a new Iterator object that contains the keys for each element in the Map object in insertion order.


Syntax of Map.keys()

The syntax of Map.keys() method is:

keys()

This keys() method of Map returns a new Iterator object that contains the keys for each element in the Map object in insertion order.

Return Type

Map.keys() returns value of type Iterator.



✐ Examples

1 Using keys() to iterate over a Map

In JavaScript, we can use the keys() method to get an iterator object and use it to iterate over the keys of a Map.

For example,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the keys() method to get an iterator object iterator for the map.
  3. Use a for...of loop to iterate over the iterator and log each key to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const iterator = map.keys();
for (const key of iterator) {
  console.log(key);
}

Output

a
b
c

2 Using keys() to convert a Map to an array of keys

In JavaScript, we can use the keys() method to convert a Map object to an array of keys.

For example,

  1. Create a new Map object map with initial key-value pairs.
  2. Use the keys() method to get an iterator object iterator for the map.
  3. Convert the iterator to an array using the Array.from() method and store it in the variable arrayOfKeys.
  4. Log arrayOfKeys to the console using console.log().

JavaScript Program

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
const iterator = map.keys();
const arrayOfKeys = Array.from(iterator);
console.log(arrayOfKeys);

Output

[ 'a', 'b', 'c' ]

3 Using keys() with a Map of objects

In JavaScript, we can use the keys() method to iterate over a Map object containing objects as keys.

For example,

  1. Create a new Map object map with initial key-value pairs where keys are objects.
  2. Use the keys() method to get an iterator object iterator for the map.
  3. Use a for...of loop to iterate over the iterator and log each key to the console using console.log().

JavaScript Program

const key1 = { id: 1 };
const key2 = { id: 2 };
const map = new Map([
  [key1, 'value1'],
  [key2, 'value2']
]);
const iterator = map.keys();
for (const key of iterator) {
  console.log(key);
}

Output

{ id: 1 }
{ id: 2 }

Summary

In this JavaScript tutorial, we learned about keys() method of Map: the syntax and few working examples with output and detailed explanation for each example.