Home » JavaScript Tutorial

Maps vs Objects in JavaScript

JavaScript | Maps vs Objects: In this tutorial, we are going to learn about the maps and objects in JavaScript and what are the differences between Maps and Objects?
Submitted by Siddhant Verma, on December 04, 2019

JavaScript Objects vs Maps

Objects are super popular in JavaScript so it's not a term you are hearing for the first time even if you're a novice JS developer. Objects, in general, are a very common data structure that is used very often unlike maps. Maps are rarely ever used, you might think, however quite contrary to these maps are even more popular when it comes to building applications. In this article, we'll talk briefly about maps, what they are, how and where they are used? We'll then look at the maps in detail in JavaScript and then finally compare them with objects, which will be our main goal since both of them are quite similar.

Let's first understand what maps are, in general. The map is an abstract data structure that stores key-value pairs of any type where every key is unique. For example, let's say we have a list of students and their roll numbers starting from 1 till 50. We can store this data inside a map where our keys will be the roll numbers and the names of students as their corresponding values.

    Key              Value
    1   ---->      Gengi
    2   ---->      Harry
    3   ---->      Sam
    4   ---->      Jake
    5   ---->      Fuzzy
    And so on,

You might say why not store this data inside a simple array and the index could act as the roll no? True, we can. Maps are very similar to arrays in the sense that our keys are mapped to a certain value. However, let's say we now want to map a student ID with a student name,

    Key                  Value
    stud_19_1   ---->   Gengi
    stud_18_7   ---->   Harry
    stud_19_2   ---->   Sam
    stud_19_11  ---->   Jake
    stud_18_3   ---->   Fuzzy

Student ID represents, say the roll number of a student along with the student's batch. This information can't be interpreted as an index since arrays will always have a numeric index. Here, we can use maps to store this data as our key is not an integer or a number but an alphanumeric or a string.

Let's suppose now that we want to store the age and names of students and map a student's name to their age. We can store age as the key and name as the value. However, a large number of students will have the same age. This is the constraint in maps which remarkably distinguishes it from other data structures that maps can only contain unique keys. If we have Harry and Sam both having the age of 14, we can either store 14 ---> Harry or 14 ----> Sam, not both. You might say we can take the names as key but then again, there could be two students with the same name having the same or different age.

So maps are used where we are sure that we need to store key-value pairs and every key is unique. Maps are built in a way to perform search operations faster as they take up a large amount of space to achieve this. This is why they are also referred to as hashmaps. An important use case would be the contacts in your smartphone. The reason why you can quickly search for a contact on the list is that they are probably implemented as a hashmap with name as the key and value as their phone number. You can have an array of values about a key too but the underlying principle is that you cannot save a different or the same number with a name that already exists in the contact list. A workaround would this would be a hashed string consisting of the contact name and the timestamp (the moment at which that contact was created) that way you can store duplicate names and still perform super fast search operations!

Let's move to objects now. We know everything in JS is an object that belongs to the object class. So are maps. There's the first difference: Maps are an instance of objects however vice versa is not true.

const myMap = new Map([
    [1, 'Gengi'],
    [2, 'Fuzzy']
]);
console.log(myMap instanceof Object);

Output

 true

Since we're on it, this is how we create a new map in JS using the new keyword followed by the data structure name, much like we create objects using the new keyword and specify the key-value pairs inside the method.

const myObj = new Object();
console.log(myObj instanceof Map);

Output

false

A stark difference between the two (now all our discussion would be specific to JS) is how we create them? Maps are fairly new and can only be created using the new keyword followed by the Map constructor method. However, you know that objects can be created in a number of ways.

const obj1 = {
    rollno: 23,
    name: 'John'
}
undefined
const obj2 = new Object({
    rollno: 46,
    name: 'Chris'
})
const obj3 = Object.create(null);
console.log(obj1);
console.log(obj2);
console.log(obj3);

Output

{rollno: 23, name: "John"}
{rollno: 46, name: "Chris"}
{}

The syntax in the map is more general and simple wrt objects when it comes to accessing elements and checking if they exist inside the data structure,

myMap.get(1);
obj1["name"];

Output

"Gengi"
"John"
myMap.has(1);
myMap.has(46);

Output

true
false

In objects this becomes a bit more tedious,

isExist='name' in obj1;
isExist='age' in obj1;

Output

true
false

To add elements in a map,

myMap.set(46, 'John');
console.log(myMap);

Output

Map(3) {1 => "Gengi", 2 => "Fuzzy", 46 => "John"}

Both maps and objects in a similar way perform the insert operation in O(1) time.

delete obj2.rollno;
myMap.delete(46);
console.log(obj2);
console.log(myMap);

Output

{name: "Chris"}
Map(2) {1 => "Gengi", 2 => "Fuzzy"}

Deleting single element is quite similar with both performing it in O(1) time, however, to remove all the elements from an object we'll have to traverse the object and delete all elements one by one, whereas we can directly do so using the clear() method in map,

myMap.clear();
console.log(myMap);

Output

Map(0) {}

Getting the size is also relatively easier in maps.

console.log(myMap.size);
console.log(Object.keys(obj1).length);

Output

0
2

You might think maps have simpler syntax so why not use them everywhere? However, objects are more popular and have a direct reference with JSON. Plus storing duplicate items comes in handy when using an object. So it really depends on what your use case for the data structure is, both can do a pretty great job is used appropriately!






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.