Map.keys()

The Map.keys() method in JavaScript is used to return an iterator object that contains all the keys present in a Map object. The keys are returned in insertion order.

Syntax

</>
Copy
map.keys()

Parameters

The keys() method does not accept any parameters.

Return Value

The keys() method returns an iterator object that contains all the keys of the Map in their original insertion order.


Examples

1. Retrieving Keys from a Map

This example demonstrates how to use keys() to get an iterator over the keys in a Map.

</>
Copy
const myMap = new Map();
myMap.set("a", 1);
myMap.set("b", 2);
myMap.set("c", 3);

const keysIterator = myMap.keys();
console.log(keysIterator.next().value);
console.log(keysIterator.next().value);
console.log(keysIterator.next().value);

Output

a
b
c
  1. myMap.keys() returns an iterator over the keys.
  2. The next() method is used to access keys sequentially.

2. Converting Keys Iterator to an Array

Since keys() returns an iterator, you can convert it into an array using the spread operator (...) or Array.from().

</>
Copy
const myMap = new Map([
    [1, "one"],
    [2, "two"],
    [3, "three"]
]);

const keysArray = [...myMap.keys()];
console.log(keysArray);

Output

[1, 2, 3]

3. Iterating Over Keys with for...of

The keys() method is often used with a for...of loop to iterate over all keys.

</>
Copy
const myMap = new Map([
    ["name", "Alice"],
    ["age", 25],
    ["city", "New York"]
]);

for (const key of myMap.keys()) {
    console.log(key);
}

Output

name
age
city

4. Using keys() in a Function

The keys() method can be used in functions to extract all keys from a given Map.

</>
Copy
function getMapKeys(map) {
    return [...map.keys()];
}

const userMap = new Map([
    ["id", 101],
    ["username", "arjun_palvai"]
]);

console.log(getMapKeys(userMap));

Output

["id", "username"]

This function returns all the keys from a Map as an array.