JavaScript Map Object
Subject: JavaScript
In JavaScript, a Map is a built-in object designed to hold key-value pairs. Unlike plain objects, a Map allows keys of any type (including objects, functions, and primitives), and it maintains the order in which keys are inserted.
Why Use Map Instead of Object?
- Maps can use any value as a key.
- Maps maintain insertion order.
- Maps provide reliable size and iteration methods.
Creating a Map
Setting Key-Value Pairs
Getting Values
Checking for Keys
Getting Map Size
Deleting a Key
Clearing All Entries
Iterating Over a Map
Using for...of Loop
Using forEach()
Example: Counting Word Frequency with Map
Key Takeaways
- Map keys can be any data type.
- Maps maintain insertion order.
- Use
.set(),.get(),.has(),.delete(), and.clear()to manage entries. - Maps are ideal for high-performance key-value storage with flexible key types.