The map.set()
method is used to add or update a key-value pair in a Map. If the key doesn't exist, a new entry is created. If the key already exists, its value is updated.
Example 1: Adding String Keys and Values
// Create a Map for user information.
const userInfo = new Map();
// Add user details using the set() method.
userInfo.set('firstName', 'John');
userInfo.set('lastName', 'Doe');
console.log(userInfo.get('firstName')); // Outputs: John
Explanation
This code uses set()
to add two key-value pairs to the userInfo
Map. Both the keys and values are strings, a common scenario for storing textual data.
Example 2: Using Numbers as Keys
// Create a Map to store product information by ID.
const products = new Map();
// Add products with numeric keys.
products.set(101, 'Laptop');
products.set(102, 'Mouse');
console.log(products.get(101)); // Outputs: Laptop
Explanation
This example demonstrates that Map
keys are not limited to strings. Here, numeric product IDs are used as keys to store product names.
Example 3: Using Mixed Data Types
// Create a Map to store diverse data about a file.
const fileMetadata = new Map();
// Set metadata with various key and value types.
fileMetadata.set('name', 'document.pdf');
fileMetadata.set('size', 2048);
fileMetadata.set('isReadOnly', true);
console.log(fileMetadata.get('size')); // Outputs: 2048
Explanation
This code illustrates the flexibility of Maps in handling different data types for both keys and values within the same collection.
Example 4: Using Objects as Keys
// Create a Map to associate DOM elements with custom data.
const elementData = new Map();
// Define two object keys.
const elementA = { id: 'a' };
const elementB = { id: 'b' };
// Set data with object keys.
elementData.set(elementA, 'Data for Element A');
elementData.set(elementB, 'Data for Element B');
console.log(elementData.get(elementA)); // Outputs: Data for Element A
Explanation
A powerful feature of Maps is the ability to use objects as keys. This example shows how two distinct object keys can map to their respective string values.
Example 5: Chaining set()
Calls
// Create a new Map and chain set() calls for concise initialization.
const userPreferences = new Map()
.set('theme', 'dark')
.set('notifications', 'enabled')
.set('language', 'en-US');
console.log(userPreferences.get('theme')); // Outputs: dark
Explanation
The set()
method returns the Map object itself, allowing for method chaining. This provides a fluent and readable way to populate a Map with multiple entries.
Example 6: Updating an Existing Value
// Create a Map to track the status of a process.
const processStatus = new Map();
// Set the initial status.
processStatus.set('progress', 50);
// Update the status.
processStatus.set('progress', 75);
console.log(processStatus.get('progress')); // Outputs: 75
Explanation
This example shows how calling set()
with an existing key ('progress') updates its value. This is useful for tracking state that changes over time.
Example 7: Storing Functions as Values
// Create a Map to store a collection of utility functions.
const commandPalette = new Map();
// Define some functions.
const saveFile = () => console.log('File saved!');
const openFile = () => console.log('File opened!');
// Set functions as values.
commandPalette.set('save', saveFile);
commandPalette.set('open', openFile);
// Retrieve and execute a function.
commandPalette.get('save')(); // Outputs: File saved!
Explanation
Maps can store functions as values, which is useful for creating dispatch tables or command patterns. Here, string keys are mapped to executable functions.