Get the first element of a Map in JavaScript

To get the first element of a Map object, you can use the entries() method to obtain an iterator object containing the map's keys and values. After that, call the next() method on the iterable to retrieve the first element of the Map:

const map = new Map([
  ['name', 'Alex Hales'],
  ['age', 27],
  ['country', 'United States']
])

const first = map.entries().next()

console.log(first.value)
// [ 'name', 'Alex Hales' ]

The entries() method returns an iterator object containing the [key, value] pairs for all elements in the Map object in insertion order. The next() method returns the next element in the iterable object.

Since we call the next() method only once on the iterable, it returns the first element in the sequence.

An alternate approach is to use the Array.from() method or spread operator (...) to convert the Map object into an array and then access the first element at index 0:

const map = new Map([
  ['name', 'Alex Hales'],
  ['age', 27],
  ['country', 'United States']
])

const first = Array.from(map)[0] // OR [...map][0]

console.log(first)
// [ 'name', 'Alex Hales' ]

Finally, you can also use the array destructuring with the keys() and values() method to obtain the first key and value in the Map object:

const map = new Map([
  ['name', 'Alex Hales'],
  ['age', 27],
  ['country', 'United States']
])

const [firstKey] = map.keys()
console.log(firstKey) // name

const [firstVal] = map.values()
console.log(firstVal) // Alex Hales

Read this article to learn more about the Map object and how to create collections of key-value pairs in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.