JavaScript Maps

JavaScript Tutorial

JavaScript Maps

In JavaScript Maps is a collection of key-value pairs in JavaScript. Unlike objects, Maps allow:

✔ Any type of key (objects, functions, numbers, strings)
✔ Values to be stored in insertion order
✔ Easy size checking


🧩 Creating a Map


➕ Adding Key-Value Pairs

Use the .set() method:


🔍 Getting Values

console.log(map.get("name")); // Alice
console.log(map.get(1)); // Number Key

❓ Checking Keys


🗑 Removing Items


🧹 Clear All Items


📏 Size of a Map


🔁 Iterating Through a Map

Loop through keys and values:


 


Using forEach():


📌 Useful Methods Summary

Method Description
set(key, value) Adds or updates entry
get(key) Returns value for the key
has(key) Checks if key exists
delete(key) Removes key/value
clear() Removes all entries
size Number of items

🆚 Map vs Object

Feature Map Object
Key type Any type String/symbol only
Ordered Yes No guarantee
Iterable Yes No (needs conversion)
Size tracking size property Must count manually

⭐ Practical Example: Counting Occurrences


 

Output:

Map(3) { 'apple' => 2, 'banana' => 2, 'orange' => 1 }

You may also like...