Map vs Object in JavaScript
Last Updated :
18 Nov, 2024
In JavaScript, both Map and Object store key-value pairs.
- Maps offer better performance for frequent additions or deletions. For read heavy operations where strings are keys, Objects provide better performance.
- Object allows only Strings and Symbols as keys, but Map maintains key order and allows any data type (including objects) as keys.
- JSON directly supports Objects. To create a JSON object from map, we first need to convert the map into an object.
- Maps maintain order of insertion of items. Objects are not ordered.
- Maps support functions like get(), set(), has() and delete() which are not there in Objects.
- Maps also have size property to quickly get the size.
- Object have properties inherited from Prototype Chain and we need to be careful to make sure that the key names that we use do not clash with existing properties. For example toString(). Please see the below code. Maps do not require such caution and simpler to use.
JavaScript
const obj = {};
// Add a key named "toString" to the object.
obj.toString = function () {
return "Custom toString method";
};
// Attempt to call the custom `toString` method.
console.log(obj.toString()); // Output: "Custom toString method"
// Delete the custom `toString` property.
delete obj.toString;
// Call the default `toString` method from Object.prototype.
console.log(obj.toString()); // Output: "[object Object]"
OutputCustom toString method
[object Object]
Feature | Map | Object |
---|
Key Types | Any data type, including objects | Limited to strings and symbols. If we provide other types, for example a number, it auto converts to strings. For example obj[55] = true is treated as obj["55"] = true. |
Iteration | Supports easy iteration (for...of , forEach ) | Iteration through keys/values possible (for...in , Object.keys() ) |
Size | Has a size property | No direct size property, count keys manually |
Performance | Efficient for frequent additions/removals | Efficient for frequent reads with string keys. |
Methods | Provides various built-in methods (set , get , delete , has , etc.) | Limited built-in methods for manipulation |
Key Order | Maintains the order of insertion | No guaranteed order of keys (may vary across JavaScript engines) |
Use Cases | Versatile, supports various key types | Simple key-value pairs, plain data structures |
Map vs Object Examples
Example 1: In this example we demonstrates storing and accessing employee information using both a Map and an Object. It highlights the flexibility of Map with methods like set() and get() for retrieving data.
JavaScript
// Using Map to store employee information
let employeeMap = new Map();
employeeMap.set('John', { age: 30, department: 'IT' });
employeeMap.set('Alice', { age: 35, department: 'HR' });
// Accessing employee information using Map
console.log("Employee information using Map:");
console.log(employeeMap.get('John'));
console.log(employeeMap.get('Alice'));
// Using Object to store employee information
let employeeObject = {
John: { age: 30, department: 'IT' },
Alice: { age: 35, department: 'HR' }
};
// Accessing employee information using Object
console.log("\nEmployee information using Object:");
console.log(employeeObject['John']);
// Output: { age: 30, department: 'IT' }
console.log(employeeObject['Alice']);
OutputEmployee information using Map:
{ age: 30, department: 'IT' }
{ age: 35, department: 'HR' }
Employee information using Object:
{ age: 30, department: 'IT' }
{ age: 35, department: 'HR' }
Example 2: In this example we demonstrates storing and accessing user preferences using both a Map and an Object. It highlights how data is stored and retrieved.
JavaScript
// Using Map to store user preferences
let userPreferencesMap = new Map();
userPreferencesMap.set('John', { theme: 'dark', language: 'English' });
userPreferencesMap.set('Alice', { theme: 'light', language: 'French' });
// Using Object to store user preferences
let userPreferencesObject = {
John: { theme: 'dark', language: 'English' },
Alice: { theme: 'light', language: 'French' }
};
// Accessing user preferences using Map
console.log("User preferences using Map:");
console.log(userPreferencesMap.get('John'));
// Output: { theme: 'dark', language: 'English' }
console.log(userPreferencesMap.get('Alice'));
// Output: { theme: 'light', language: 'French' }
// Accessing user preferences using Object
console.log("\nUser preferences using Object:");
console.log(userPreferencesObject['John']);
console.log(userPreferencesObject['Alice']);
OutputUser preferences using Map:
{ theme: 'dark', language: 'English' }
{ theme: 'light', language: 'French' }
User preferences using Object:
{ theme: 'dark', language: 'English' }
{ theme: 'light', langu...
Similar Reads
Set vs Map in JavaScript In JavaScript, Set and Map are two types of objects that are used for storing data in an ordered manner. Both these data structures are used to store distinct types of data inside the same object. In Maps, the data is stored as a key-value pair whereas in Set data is a single collection of values th
2 min read
Objects in Javascript An object in JavaScript is a data structure used to store related data collections. It stores data as key-value pairs, where each key is a unique identifier for the associated value. Objects are dynamic, which means the properties can be added, modified, or deleted at runtime.There are two primary w
4 min read
How to Recursively Map Object in JavaScript ? Recursively mapping objects in JavaScript involves traversing through nested objects and applying a function to each key-value pair. This process allows for transforming the structure of an object according to a specific logic or requirement. Below are the approaches to recursively map an object in
3 min read
JavaScript Map values() Method The JavaScript map.values() method is used to return a new Iterator object that contains the value of each element present in Map. The order of the values are in the same order that they were inserted into the map.Syntax:myMap.values()Parameters: This method does not accept any parameters.Example 1:
2 min read
JavaScript Map set() Method The JavaScript map.set() method is used to add key-value pairs to a Map object. It can also be used to update the value of an existing key. Each value must have a unique key so that they get mapped correctly.Syntax:GFGmap.set(key, value);Parameters:This method accepts two parameters as mentioned abo
2 min read
JavaScript Map size Property Map is a collection of elements where each element is stored as a Key, value pair. The Map.size property returns the number of key, and value pairs stored in a map.SyntaxmapName.sizeReturn ValueAn integer representing the number of key, value pairs stored in a map.The below examples illustrate the M
1 min read