How to Get the First Element of a Map in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 05 20212 min read

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

In the code snippet we called the keys() method on the map to get an iterator that contains the keys of each element in the map.

We then use destructuring assignment to get the first key and assign it to a variable.

To get the value of the first element, we repeat the same process, but call the 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]

In the code snippet we use the spread syntax to convert the map into an array and access 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 just 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]

In the code snippet, we first get an iterator containing the elements of the map.

We then an object containing the value of the first iteration.

Finally, we access the value property on the object to get an array of the key and value of the first element in the map.

The last approach is harder to read and less intuitive than the first 2. It's best to avoid getting into the implementation details of maps, unless you have to.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.