In JavaScript, we often encounter the need to manage key-value pairs. When discussing key-value pairs, the predominant approach is to use Objects for their storage. However, with the introduction of ECMAScript 2015, a new feature known as Map was added, which also serves the purpose of storing key-value pairs.
In this article, we will explore the differences between JavaScript Map and Object. Both Map and Object in JavaScript serve the purpose of storing data in the form of dynamic collections comprised of key-value pairs. We will examine maps and objects individually to gain a clearer understanding.
What is a map?
ES6, which stands for ECMAScript 2015, is a specification for scripting languages that introduces a feature known as "Map." The Map serves as a data structure in JavaScript designed to maintain a collection of unique data represented as key-value pairs. This implies that a Map cannot contain duplicate values.
The syntax for creating a JavaScript Map is as follows:
const product = new map();
prod.set('name', 'Laptop');
prod.set('price', 55000);
What is an Object?
The Object functions similarly to a map, serving as a data structure designed to hold unique information organized as key-value pairs. However, there are some differences between an Object and a map that we will explore further in this article.
Below is the syntax used for creating a JavaScript Object:
const product = {
name: 'Laptop';
price: 55000;
Map VS Object
1. Based on construction
Constructing a Map:
The creation of the Map can be accomplished in a singular manner, detailed below:
Code:
var map = new Map([ [6, 8], [5, 4] ]);
console.log(map instanceof Object);
var obj = new Object();
console.log(obj instanceof Map);
Output:
Constructing an Object:
There are multiple methods through which we can instantiate an Object in JavaScript, including but not limited to the following:
- Constructor: An Object can be created using a constructor function.
Code:
var ob = new Object();
var ob = new Object;
console.log(ob);
Output:
In the output displayed below, we can observe an object that is devoid of any content.
- Object creation using a direct literal: An Object can be instantiated by employing a direct literal approach.
Code:
var ob = {};
var ob = {1:"Object Name", 2:"Sample"};
console.log(ob);
Output:
An instance of an Object has been instantiated, as demonstrated by the output shown below.
- create: An Object can be instantiated using a direct literal syntax.
Code:
function products() {
this.name = 'product 1';
this.price = 25000;
}
function refrigerator() {
products.call(this);
}
refrigerator.prototype = Object.create(products.prototype);
const app = new products();
console.log(app.name);
console.log(app.price);
Output:
We can observe the Object that has been generated in the result displayed below.
2. Based on how to access the element:
- The get function is utilized by the Map, which is a built-in function employed for retrieving elements.
Syntax:
map.get(1);
- The term "key" was employed in conjunction with a "dot" operator to retrieve elements from the Object.
Syntax:
obj.id;
obj[id];
3. Based on the type of key:
- Map consists of a key-value pair in which the key can be of any type such as primitive type, function or object.
- Object contains a key-value pair in which the key can be of one string type. If you define a key of any other type then also it will be converted into a string.
The ### 4. Based on how to check whether a key exists already or not:
- Map employs the has method, a built-in function designed to verify the presence of a specific key.
Syntax:
map.has(1);
The has function produces a boolean result, which can either be true or false.
- Object employs the "===" operator to perform its operations.
Syntax:
var doExist = obj.1 === undefined;
It returns boolean value either true or false.
5. Based on how to add a new element:
- Map employs the set function to incorporate a new element.
Syntax:
map.set(6, 9);
- Object introduces a new element straightaway.
Syntax:
obj["Sample"]="Map VS Object";
6. Based on how to get size:
- While the Map object automatically adjusts its size, we can employ the following syntax to retrieve its size.
Syntax:
console.log(map.size);
- Object employs Object.keys to determine its size.
Syntax:
console.log(Object.keys(obj).length);
It returns the size of the elements.
7. Based on how to delete an element:
- The delete method is employed by Map to eliminate an element.
Syntax:
console.delete(1);
- Object employs the delete keyword to remove solely the property associated with the element.
Syntax:
delete obj.property; or
delete obj.[property];
8. Based on how to read key and value pairs:
- The Map interface employs the keys method to retrieve a collection of keys, the values method to acquire a collection of values, and the entries method to obtain the key-value pairs.
Syntax:
const map = new Map([[1, "Apple"], [2, "Mango"]]);
console.log(map.keys());
console.log(Array.from(map.keys()));
console.log(map.values());
console.log(Array.from(map.values()));
console.log(map.entries());
console.log(Array.from(map.entries()));
Output:
- The Object class provides a keys method for retrieving the keys, a values method for obtaining the values, and an entries method for accessing the key-value pairs.
Syntax:
const fruits = { 1: "Apple", 2: "Mango" };
console.log(Object.keys(fruits));
console.log(Object.values(fruits));
console.log(Object.entries(fruits));
Output:
9. Based on iteration:
- There are multiple methods available for traversing elements, but we will focus on employing the for loop and forEach loop to iterate through the elements contained within a map.
Syntax of using the for loop:
for (const [ key, value ] of map) {
console.log(value);
};
Syntax of using the forEach loop:
map.forEach((value, key) => console.log(value));
- There are numerous methods to traverse elements; however, we will focus on using the for loop and the forEach loop to iterate through the elements contained within an object.
Syntax of using the for loop:
for (const [key, value ] of Object.entries(obj)) {
console.log(value);
};
Syntax of using the forEach loop:
Object.entries(obj).forEach(([ key, value ]) => console.log(value));
10. Based on the conversion of them into JSON:
- Map does not support JSON because Map is a hash table, which is why a parser is created to convert Map into JSON.
- Object support JSON and permits to convert the Objects into JSON directly.
It can be asserted that Map is favored in comparison to Object due to the reasons we have previously elaborated upon.
Conclusion:
In this article, we have explored the distinctions between JavaScript Map and Object. Both Map and Object serve the purpose of storing data in key-value pairs; however, they possess notable differences. The primary distinction between the two is that Map allows for the use of complex data types as keys, whereas Object restricts its keys to the string data type exclusively.