JavaScript Map Methods – JavaScript is a versatile language, offers many methods to handle various data structures efficiently. One such powerful data structure is the Map. JavaScript Map Methods – How Does it work? Complete Guide
Introduced in ECMAScript 6 (ES6), the Map object allows you to store key-value pairs and provides numerous methods to manipulate these pairs. This article’ll dive deep into JavaScript Map methods, exploring their functionalities with detailed coding examples.
What is a Map in JavaScript?
A Map is a collection of keyed data items, just like an Object. However, the main difference between Maps and Objects is that Maps allow keys of any type, including objects, functions, and primitive data types. Additionally, Maps maintain the order of their elements based on the order of insertion.
Creating a Map
Before we explore the various methods available, let’s see how to create a Map.
// Creating a new Map
const map = new Map();
// Adding key-value pairs
map.set('name', 'John');
map.set('age', 30);
map.set('occupation', 'Developer');
// Display the map
console.log(map);
The output of the provided code is a Map object that contains the key-value pairs you added to it. When you display the map using console.log(map), it will output the Map object in a readable format. Here is what the output will look like:
Map(3) {
'name' => 'John',
'age' => 30,
'occupation' => 'Developer'
}
This output shows that the Map object has three entries with keys ‘name’, ‘age’, and ‘occupation’, each associated with their respective values ‘John’, 30, and ‘Developer’.
Maps Methods
Maps.get()
By using the maps.get() method you get the value of a key in a map with the get() method
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Maps</h1>
<h2>The get() Method</h2>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
document.getElementById("demo").innerHTML = fruits.get("apples");
</script>
</body>
</html>
Output:

Maps.set()
The set() method adds or updates an element with a specified key and value to a Map object.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Maps</h1>
<h2>The get() Method</h2>
<p id="demo"></p>
<script>
const map = new Map();
map.set('color', 'blue');
map.set('size', 'large');
console.log(map); // Map(2) { 'color' => 'blue', 'size' => 'large' }
const color = map.get('color');
console.log(color); // blue
document.getElementById("demo").innerHTML = map.get("color");
</script>
</body>
</html>
Output:

Map.size
The size property returns the number of elements in a map:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Maps</h1>
<h2>The map.size() Method</h2>
<p id="demo"></p>
<script>
const map = new Map();
map.set('color', 'blue');
map.set('size', 'large');
console.log(map); // Map(2) { 'color' => 'blue', 'size' => 'large' }
const color = map.get('color');
console.log(color); // blue
document.getElementById("demo").innerHTML = map.size;
</script>
</body>
</html>

Map.delete()
The delete() method removes a map element
maps.delete(“color”);
clear()
The clear() method removes all key-value pairs from a Map.
map.clear();
console.log(map); // Map(0) {}
Map.has()
The has() method returns true if a key exists in a map:
map.has(“size”)
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Maps</h1>
<h2>The has() Method</h2>
<p id="demo"></p>
<script>
const map = new Map();
map.set('color', 'blue');
map.set('size', 'large');
console.log(map); // Map(2) { 'color' => 'blue', 'size' => 'large' }
const color = map.get('color');
console.log(color); // blue
document.getElementById("demo").innerHTML = map.has("size");
</script>
</body>
</html>

Try this:
map.delete(“color”);
map.has(“color”);
Map.forEach()
The forEach() method invokes a callback for each key/value pair in a map:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Maps</h1>
<h2>The forEach() Method</h2>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
let text = "";
fruits.forEach (function(value, key) {
text += key + ' = ' + value + "<br>"
})
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output:

Map.entries()
The entries() method returns an iterator object with the [key,values] in a map:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Maps</h1>
<h2>The entries() Method</h2>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
let text = "";
for (const x of fruits.entries()) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Real-World Application: Counting Word Frequencies
Let’s create a real-world example where we count the frequency of each word in a given string using a Map.
function countWordFrequencies(text) {
const words = text.toLowerCase().split(/\W+/);
const wordMap = new Map();
words.forEach(word => {
if (wordMap.has(word)) {
wordMap.set(word, wordMap.get(word) + 1);
} else {
wordMap.set(word, 1);
}
});
return wordMap;
}
const text = "Hello world! Hello everyone. Welcome to the world of JavaScript.";
const wordFrequencies = countWordFrequencies(text);
wordFrequencies.forEach((count, word) => {
console.log(`${word}: ${count}`);
});
Full Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Word Frequency Counter</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
textarea {
width: 100%;
height: 150px;
margin-bottom: 20px;
}
button {
padding: 10px 20px;
font-size: 16px;
}
#output {
margin-top: 20px;
}
.word-count {
margin: 5px 0;
}
</style>
</head>
<body>
<h1>Word Frequency Counter</h1>
<p>Enter your text in the textarea below and click "Count Words" to see the frequency of each word.</p>
<textarea id="textInput"></textarea>
<br>
<button onclick="countWords()">Count Words</button>
<div id="output"></div>
<script>
function countWordFrequencies(text) {
const words = text.toLowerCase().split(/\W+/);
const wordMap = new Map();
words.forEach(word => {
if (wordMap.has(word)) {
wordMap.set(word, wordMap.get(word) + 1);
} else {
wordMap.set(word, 1);
}
});
return wordMap;
}
function countWords() {
const text = document.getElementById('textInput').value;
const wordFrequencies = countWordFrequencies(text);
const outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
wordFrequencies.forEach((count, word) => {
const p = document.createElement('p');
p.classList.add('word-count');
p.textContent = `${word}: ${count}`;
outputDiv.appendChild(p);
});
}
// Example usage of the countWordFrequencies function
const exampleText = "Hello world! Hello everyone. Welcome to the world of JavaScript.";
const exampleWordFrequencies = countWordFrequencies(exampleText);
exampleWordFrequencies.forEach((count, word) => {
console.log(`${word}: ${count}`);
});
</script>
</body>
</html>
Output:
Conclusion
JavaScript Map methods provide powerful tools for managing and manipulating key-value pairs. By leveraging these methods, you can efficiently handle data structures, perform various operations, and solve real-world problems with ease. Whether you’re counting word frequencies or maintaining a collection of unique items, Maps offer a versatile and intuitive approach to data management in JavaScript.
Understanding and mastering these methods will enhance your JavaScript coding skills, making you more adept at handling complex data operations in your projects. So, dive into the world of JavaScript Maps and explore the endless possibilities they offer!





Leave a Reply