The get() method is used to retrieve an element from a Map object in JavaScript. This method accepts the key of the element as an argument and returns the associated value. If the key is not found in the Map, it returns undefined.

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 returns a reference to that object. Any modifications made to the object will be reflected inside the Map object as well:

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 ]

To delve deeper into the Map object and discover more about creating collections of key-value pairs in JavaScript, you can refer to this article.

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