JavaScript - Map Methods Part 2: Adding and Deleting Elements

1. set() Method

The set() method adds a new key-value pair or updates an existing one.

Example:

const colors = new Map();

colors.set("red", "#FF0000");

colors.set("blue", "#0000FF");

console.log(colors);

// Map(2) { 'red' => '#FF0000', 'blue' => '#0000FF' }

// Updating the value of an existing key

colors.set("red", "#FF4500");

console.log(colors.get("red")); // #FF4500

2. delete() Method

The delete() method removes a key-value pair from the Map.

Example:

colors.delete("blue");

console.log(colors); // Map(1) { 'red' => '#FF4500' }

3. clear() Method

The clear() method removes all key-value pairs from the Map.

Example:

colors.clear();

console.log(colors); // Map(0) {}