How to get an element from a map - JavaScript

Mo Ibra

Mo Ibra

Dec 13, 2022

In this article we will learn how to get an element from a map.

It is very common to get an element from a map in JavaScript.


Problem

Now we have a problem, which is that we want to get an element from a map.

Now let's define a map like this:

// Map
const map = new Map([
    ['name', 'John'],
    ['age', 30],
]);

console.log(map);
// Map(2) { 'name' => 'John', 'age' => 30 }

And we want to get an element from his key.

How to solve this problem?

Fortunately, we have a built-in function that get elements from the map called get.


Get an element from a map using get

As we said before, we can use the get() function to get an element from a map.

Example

// Map
const map = new Map([
    ['name', 'John'],
    ['age', 30],
]);

// Get element
const ele = map.get('name');

// Print element value
console.log(ele);

Output

John

map.get() It takes the key and returns the value.


Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: