Get an element from a Map using JavaScript

You can use the get() method to get an element from a Map object in JavaScript. The get() method takes the element key as input and returns the value associated with the specified key, or undefined if the key is not found in the Map object.

const map = new Map()

map.set('name', 'John Doe')
map.set('age', 29)
map.set('job', 'UX Designer')

console.log(map.get('name')) // John Doe
console.log(map.get('age')) // 29
console.log(map.get('job')) // UX Designer

console.log(map.get('address')) // undefined

If the value associated with the specified key is an object, the get() method will return a reference to that object. Any subsequent changes made to that object will also reflect inside the Map object:

const product = { name: 'Milk', qty: 2 }
const prices = [2.99]

const items = new Map()
items.set('product', product)
items.set('prices', prices)

items.get('product').qty = 100
items.get('prices').push(4.55)

console.log(product)
// { name: 'Milk', qty: 100 }

console.log(prices)
// [ 2.99, 4.55 ]

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.