JavaScript - Map Methods Part 1: Basic Map Creation and Properties
1. Creating a Map
A Map is created using the new Map() constructor. It can either start empty or be initialized with key-value pairs.
Example 1: Empty Map
const myMap = new Map();
console.log(myMap); // Map(0) {}
Example 2: Pre-filled Map
const cities = new Map([
["New York", "USA"],
["Paris", "France"],
["Tokyo", "Japan"],
]);
console.log(cities);
// Output: Map(3) { 'New York' => 'USA', 'Paris' => 'France', 'Tokyo' => 'Japan' }
2. Properties of a Map
size Property
The size property returns the number of key-value pairs in the Map.
Example:
console.log(cities.size); // 3
Maps maintain the insertion order of their keys, unlike plain objects.
Example:
cities.set("Berlin", "Germany");
console.log([...cities.keys()]); // ['New York', 'Paris', 'Tokyo', 'Berlin']