How to Get the First Element of a Map in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the First Element of a Map in JavaScript #

To get the first element of a Map, use destructuring assignment, e.g. const [firstKey] = map.keys() and const [firstValue] = map.values(). The keys() and values() methods return an iterator object that contains the Map's keys and values.

index.js
const map = new Map(); map.set('a', 1); map.set('b', 2); const [firstKey] = map.keys(); console.log(firstKey); // 👉️ a const [firstValue] = map.values(); console.log(firstValue); // 👉️ 1

We called the keys() method on the Map to get an iterator that contains the keys of each element in the Map.

We used destructuring assignment to get the first key and assigned it to a variable.

We repeat the same process to get the value of the first element, but used theMap.values() method instead.

Another way to get the first element of a Map is to convert the Map into an array and access the element at index 0.

index.js
const map = new Map(); map.set('a', 1); map.set('b', 2); const first = [...map][0]; console.log(first); // 👉️ ['a', 1]

We used the spread syntax to convert the Map into an array and accessed the element at index 0.

This returns an array containing the key and value of the first element in the Map.

Note that converting a Map with thousands of elements into an array would be slow and inefficient if you only have to access a single element.

We can also get the first element of a Map by using some of the methods on the Map instance.

index.js
const map = new Map(); map.set('a', 1); map.set('b', 2); const iterator = map.entries(); const firstIteration = iterator.next(); // {value: ['a', 1], done: false} const first = firstIteration.value; console.log(first); // 👉️ ['a', 1]

We got an iterator containing the elements of the Map and used the next() method to get an object containing the value of the first iteration.

Lastly, we accessed the value property on the object to get an array of the key and value of the first Map element.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.