Difference between MAP and object in JavaScript

JavaScript

In this post, We are going to learn the difference between MAP and object with example.

We will be covering two types of objects in JavaScript, Map and regular objects.

A Regular Object in JavaScript is a dictionary. Whereas Map is a Hash that consists of basic lists of key-value pairs. The map contains the Unique key and value pair, MAP does not contain a duplicate pair. The MAP is a better option when it comes to iteration on a large amount of data.

Let understand the more differences between MAP and Object

1. Parent-child relationship

Map

The object is the parent class for A Map object that means we can use the object prototype in Map.

Let us understand the same with an example. If we check whether Map is an instance of Object, we will get true in output. This helps us understand that Map itself is an Object too.

const langObj = new Map();

langObj.set(1, 'C#');
langObj.set(2, 'JAVA');
console.log(langObj instanceof Object);  

Output

true

Object

We can’t use the Map prototype in Object. The map is a child class of objects so it can’t be used in the parent class.

Let us check the same with an example. If we check whether the obj is an instance of Map, we will get false in output.

var obj = {1:"C#", 2:"JAVA"}; 

console.log(obj instanceof Map);  

Output

false

2. Default key Behavior

Default key does not exist in Map

The map object does not have a default Key. All keys are explicitly inserted into it. So this needs to be taken care of when creating a Map.

Here is an example of the same showing how to create Map object and then insert keys to it:

const langObj = new Map();

langObj.set(1, 'C#');
langObj.set(2, 'JAVA');
for (let keyvalue of langObj) {
  console.log(keyvalue)
}

Output

[ 1, 'C#' ]
[ 2, 'JAVA' ]

But Object contain Default Keys

Normal Objects contains a prototype(it is a procedure by which JavaScript objects inherit features from one another). It has an implicit key that may be a conflict with keys that Object holds. So this should be avoided. We will see next how we can avoid it.

Let us understand with Example:

const numbers = { 1: 'one',2: 'Two',3: 'Three'};

for (const num in numbers) {
   if (numbers.hasOwnProperty(num)) 
   {
           console.log(num + " written as = " + numbers[num]);
   } }

Output

"1 written as = one"
"2 written as = Two"
"3 written as = Three"

We can get rid of the prototype by declaring the prototype of the object explicitly. We can Bypass the prototype by passing “null” to create() method.

Let us understand with example

const numbers = Object.create(null);
numbers.one = 1;
numbers.two = 2,
numbers.three = 3;
for (const num in numbers) {
 if (numbers.hasOwnProperty(num))  //it will thrown an error
   {
         console.log(num + " written as = " + numbers[num]);
   }
}

3. Instance Creation

Create a Map object

We can create a Map object just by one way as shown in below example.

const langObj = new Map();
langObj.set(1, 'C#');
langObj.set(2, 'JAVA');
console.log(langObj)

Output

Map { 1 => 'C#', 2 => 'JAVA' }

Create an Object

We can create a object by different ways as shown below.

  1. Using literal
var obj = {1:"C#", 2:"JAVA"}; 
console.log(obj);

Output

{ '1': 'C#', '2': 'JAVA' }

2. Using constructor

const obj = new Object({1:"C#", 2:"JAVA"}); 
console.log(obj);

Output

{ '1': 'C#', '2': 'JAVA' }

3. Using Create() Method

const numbers = Object.create(null);
numbers.one = 1;
numbers.two = 2,
numbers.three = 3;
console.log(numbers)

Output

[Object: null prototype] { one: 1, two: 2, three: 3 }

4. Keys Type

Map’s object keys can be of any datatypes(functions,object and primitive)

Below is the List of Primitives Types and some of the examples of primitive types.

  • String
  • Number
  • BigInt
  • Boolean
  • Undefined
  • Symbol
  • null is seemingly primitive
let State_obj= { state: "CA" };
const langObj = new Map();

//int as key
langObj.set(1, 'C#');
langObj.set(2, 'JAVA');

//string as a key
langObj.set('3', 'JS');
langObj.set('four', 'Go');
//boolean as a key
langObj.set(true, 'Python');
langObj.set(false, 'Rust');

//object as a key
langObj.set(State_obj,12);

//undefind as a key
langObj.set(undefined,'key type undefined');

console.log(langObj.get(State_obj))
console.log(langObj.get(1))
console.log(langObj.keys())


Output

12
C#
[Map Iterator] {
  1, 2,'3','four', true,  false,  { state: 'CA' },
  undefined
}

Nan as key in Map

const langObj = new Map();
langObj.set(1, 'C#');
langObj.set(2, 'JAVA');
langObj.set(NaN,'nan as a key')
langObj.get(NaN) 

Output

nan as a key

Keys types in Object

when it comes to normal Objects then its a little different. In object data type for object keys, the data type must be string or symbol.

As you can see we have defined an object with int as keys types. But whiling getting obj values the keys 1,2 are in coming out as a string. This behavior of Object creates inconsistent datatypes.

const obj = new Object({1:"C#", 2:"JAVA"}); 
console.log(obj);

Output

{ '1': 'C#', '2': 'JAVA' }

5.Insertion orders

A map object remembers the insertion order. It iterates the order of its elements that was used during insertion.

Let us understand with example

const langObj = new Map();
//int as key
langObj.set(1, 'C#');
langObj.set(2, 'JAVA');

//string as a key
langObj.set('3', 'JS');
langObj.set('four', 'Go');

for (let [key, value] of langObj) {
  console.log(key + ' = ' + value)
}

Output

1 = C#
2 = JAVA
3 = JS
four = Go

Order of key in Object

It is completely different in case of normal objects. Normal objects does not remember insertion order.

6. Property to get size

The size of map object can be easily calculated using size property.

const langObj = new Map();

//int as key

langObj.set(1, 'C#');
langObj.set(2, 'JAVA');

console.log('size of map = '+langObj.size)

Output

size of map = 2

Size of Object

In an object, there is no property to get the size of the object we have to manually code to get its size.

const obj = new Object({1:"C#", 2:"JAVA"});
console.log('Size of obj = '+Object.keys(obj).length)

Output

Size of obj = 2

7. Simple Iteration Ways

A map object by default can be iterated easily. So we do not need to know its keys and values to iterate over it. We have different methods available to do the iteration job easily.

Different Methods in Map object to return new iterator on

  • keys():- return a new map iterator object that contains keys of the element in the map.
  • values(): return a new map iterator object that contains values of each key in the map object.
  • entries(): return a new map iterator object that contains key-values of the map object.

Let us understand with example

const langObj = new Map();
//int as key
langObj.set(1, 'C#');
langObj.set(2, 'JAVA');

//string as a key
langObj.set('3', 'JS');
langObj.set('four', 'Go');

//for of loop
console.log('for of loop \n')
for (const keyvalue of langObj) {
  console.log(keyvalue)
}
console.log('\n')
//keys on map object
console.log(langObj.keys())
//values of map object
console.log(langObj.values())
//key keyvalues of ma object
console.log(langObj.entries())

Output

for of loop 

[ 1, 'C#' ]
[ 2, 'JAVA' ]
[ '3', 'JS' ]
[ 'four', 'Go' ]


[Map Iterator] { 1, 2, '3', 'four' }

[Map Iterator] { 'C#', 'JAVA', 'JS', 'Go' }

[Map Entries] {
  [ 1, 'C#' ],
  [ 2, 'JAVA' ],
  [ '3', 'JS' ],
  [ 'four', 'Go' ]
}

Iterating an object

When it comes to normal objects, It returns any array of key-value pairs. To iterate an object we first need to get its key then we can iterate.

A different way to convert an object into an array
1.Object.keys(): It returns an array of keys
2.Object.values(): It returns an array of values
3.Object.entries(): It returns an array of key-value pairs.

const obj = new Object({1:"C#", 2:"JAVA"});
console.log('for in loop')
for (const key in obj) {
  console.log(`${key}: ${obj[key]}`)
}

console.log('\n')

//return an array of keys
console.log(Object.keys(obj))

//return an array of values
console.log(Object.values(obj))

////return an array of keys-values
console.log(Object.entries(obj))

Output

for in loop
1: C#
2: JAVA


[ '1', '2' ]
[ 'C#', 'JAVA' ]
[ [ '1', 'C#' ], [ '2', 'JAVA' ] ]

Performance

The Map is an excellent option to iterate large amounts of data. Map support built-in iteration and maintain the insertion order.so Map performs well in the iteration. If we are working with JSON data Object is a better option.

Conclusion

We can consider Map work as an Object with some advanced features like no restriction on the key types, it maintains the insertion order. We can’t say MAP is a replacement but some limitations of Object can be overcome by MAP.