Member-only story
Here’s a comprehensive guide on JavaScript Map
objects, covering everything from basic usage to advanced features:
Not a Medium member? Read this article here
1. What is a JavaScript Map
?
A Map
is a built-in JavaScript object that holds key-value pairs, where both keys and values can be of any data type. Unlike regular objects, Map
retains the order of elements and allows non-string keys.
Key Differences from Objects:
Map
allows any type of key (objects, functions, etc.).- Maintains insertion order of elements.
- Provides built-in methods for iteration and manipulation.
2. Creating a Map
You can create a Map
using the new Map()
constructor.
Syntax:
const myMap = new Map();
Example:
const userMap = new Map([
['name', 'Alice'],
['age', 30],
['isAdmin', true]
]);
console.log(userMap); // Map(3) { 'name' => 'Alice', 'age' => 30, 'isAdmin' => true }