This article was translated by the technical team at ShowmeBug, a technology assessment and online Coding interview platform.

In JavaScript, objects and maps are both dynamic collections of key-value pairs. Although the two definitions are similar, there are many differences. Let’s take a look at it with me

1. Different construction modes

The easiest way to create an Object in JavaScript is through a literal.

const smbObj = {
  1: 'ShowMeBug',
  2: 'ShowMeMoney'  
};

Map is created using the built-in constructor Map.

const smbMap = new Map([
  [1, 'ShowMeBug'],
  [2, 'ShowMeMoney']
]);

Next, I’ll use “objects” or “object maps” to refer to collections of keys and values created through literals, and “maps” to refer to mappings created through the built-in constructor Map.

2. The key in the object is a string. The key in the map can be of any type

Object is a collection of key-value pairs, but a key can only be a string. The key of a Map can be of any type.

For example, if you use a number as the Object key, that number will be converted to a string.

Because the key has been converted to a string, the result will be the same whether we get the number 1 or the value of the string ‘1’.

console.log(smbObj[1]);
//'ShowMeBug'
console.log(smbObj['1']);
//'ShowMeBug'

The key of a Map can be of any type. The key of the number 1 is not the same as the key of the string ‘1’.

console.log(smbMap[1]);
//'ShowMeBug'
console.log(smbMap['1']);
//undefined

The key is unique, both for the object and for the map. There cannot be two properties with the same key in an object, and there cannot be two entries with the same key in a map.

3. Objects inherit extra keys from the stereotype

Another difference is that objects created using literals inherit a set of key-value pairs from Object.prototype.

If you print Object.prototype, you will find that it also has hasOwnProperty, isPrototypeOf, toLocaleString, toString, etc.

console.log(Object.prototype);

Objects created with literals also have these properties. An empty object {} is not really empty. Take a look at the following code.

const socalledEmptyObject = {}; console.log(socalledEmptyObject['toString']); // LOGON () {[Native Code]}

We create a so-called “empty” object, but we can access the toString key on it. Object mappings are best created using Object.create(null).

const emptyObject = Object.create(null);
console.log(emptyObject['toString']);
//undefined

Object.create(null) builds objects that have no prototype.

4.Map preserves the order of keys; objects do not

The original order of the key-value pairs is preserved in the Map, but not in the object.

const smbObj = {
  2: 'ShowMeMoney',
  1: 'ShowMeBug'  
};

const keys = Object.keys(smbObj);
console.log(keys);
//["1", "2"]

const keyValuePairs = Object.entries(smbObj);
console.log(keyValuePairs);
//["1", "ShowMeBug"]
//["2", "ShowMeMoney"]

Notice that when the object is created, key 2 appears before key 1. But when retrieving all keys, 2 comes after 1.

Let’s create a similar collection using the Map constructor. This time the original order of the keys is preserved.

const smbMap = new Map([
  [2, 'ShowMeMoney'],
  [1, 'ShowMeBug']
]);

const keys = smbMap.keys();
console.log(keys);
//MapIterator {2, 1}

const keyValuePairs = smbMap.entries();
console.log(keyValuePairs);
//MapIterator {2 => "ShowMeMoney", 1 => "ShowMeBug"}

5.Map provides a better interface to access key-value pairs

To obtain

Accessing properties on an object can be done with the dot or square bracket operators. In this example, because the key is a number, you can only use the square bracket operator.

smbObj[1];
//'ShowMeBug'

On a Map, you need to use the get(key) method to get the value.

smbMap.get(1);
//'ShowMeBug'

Check if the key exists

A Map can use has(key) to check whether a key exists.

smbMap.has(1);
//true
smbMap.get(3);
//false

Object can be used with hasOwnProperty(key) method.

smbObj.hasOwnProperty(1);
//true
smbObj.hasOwnProperty(3);
//false

Add a key-value pair

Use set(key, value) to add a new key-value pair to the Map.

smbMap.set(3, 'ShowMeFeature'); 
//{1=>'ShowMeBug', 2=>'ShowMeMoney', 3=>'ShowMeFeature'}

For objects, we use square brackets or dot operators to add new key-value pairs.

smbObj[3] = 'ShowMeFeature';
//{ 1: 'ShowMeBug', 2: 'ShowMeMoney', 3: 'ShowMeFeature'};

Delete key-value pairs

Map can delete key-value pairs through the delete(key) method.

smbMap.delete(1);

Objects can be used with the delete operator.

delete smbObj[1];

Read the number of key-value pairs

Map has the size property to keep track of the number of internal key-value pairs.

console.log(smbMap.size);

Object has no specific method for getting the number of key-value pairs. We need to use an external helper function like Object.keys().

const size = Object.keys(smbObj).length;
console.log(size);

Objects need helper functions to access key-value pairs

We can use the forEach method to traverse the entries in the Map.

const smbMap = new Map([
  [1, 'ShowMeBug'],
  [2, 'ShowMeMoney']
]);



smbMap.forEach((value, key)=>{
   console.log(`${key} - ${value}`)
});
//1 - ShowMeBug
//2 - ShowMeMoney

For objects, we can use the object.entries () helper function to iterate.

Object.entries() returns all the properties of the Object as an array of [key, value] key-value pairs. Once you have this array, you can use array methods like forEach.

const smbObj = {
  1: 'ShowMeBug',
  2: 'ShowMeMoney'  
};

Object
  .entries(smbObj)
  .forEach(([key, value])=>{
    console.log(`${key} - ${value}`)
  });
//1 - ShowMeBug
//2 - ShowMeMoney

7.JSON supports objects, but not maps

const smbObj = {
  1: 'ShowMeBug',
  2: 'ShowMeMoney'  
};

const json = JSON.stringify(smbObj);
console.log(json);
//{"1":"ShowMeBug","2":"ShowMeMoney"}

JSON does not support maps, and the result of serialization is an empty object.

const smbMap = new Map([ [1, 'ShowMeBug'], [2, 'ShowMeMoney'] ]); const json = JSON.stringify(smbMap); console.log(json); / / {}

conclusion

Objects in JavaScript are called hash mappings in other languages. The time required to access the key in the mapped object is O(1), which means that the time required to retrieve the key is constant regardless of the amount of data in the object map.

Whether these key-value sets are created with Map constructors or object literals, they are primarily used to search for data quickly, the key access time is O(1), and retrieving the key does not require scanning all the data.

Map provides a better interface for managing key-value pairs. Map is a better choice for scenarios where entries need to be added and removed. If you create a key-value set just to search for the key, then the object is enough.

7 Differences Between Objects and Maps in JavaScript