Difference between JavaScript Map and Object

Object and Map both allow you to store key value pairs, retrieve values and delete the keys. Objects have always existed in JavaScript, so they have served the purpose of Map historically but in today’s video we will be covering 4 differences between JavaScript Map and Object.

Full Transcript

00:00 Hi there! welcome to the JavaScript series and I'm Deeksha Sharma from bonsaiilabs. Today, in this video we will be covering four differences between JavaScript Map and Object. Map is a part of keyed collection in JavaScript, which means that this data structure holds data in the form of a key and a corresponding value, whereas an Object is a collection of properties where every property also consists of a key and a value. Are you thinking if both of them holds the key value pairs, then what's the difference? There are few, let's go over them. The first difference is based on the type of key. JavaScript Map allows you to have a key value pair where the key could be a primitive type, an object or even a function, but with Objects where every property consists of a key value pair, you could only have the key of type String, so even if you assign a key of type Number, it will be converted to String.

00:51 Another difference is in the way we can iterate on them. Map is a built in a iterable in JavaScript, which means you can loop over every element in the Map using forEach loop. So if you know beforehand that you might end up iterating over key value pairs, then consider using Map. The Object on the other hand is not iterable. To loop over every property in the Object. We need to get hold of either entries, keys, or values which are returned as arrays and then iterate over them. The third difference is in the way we get the size. With Map, there is an out of the box size property available which returns the total number of entries in the Map, but there is no direct method or property to get the size of the Object, just like iteration process, we need to get hold of the entries, keys or values in the Object and then calculate the length. The fourth difference is in the way you convert them into a JSON String. Since Map is a pure hash table, there is no support for JSON directly. You need to provide your own parser to convert a Map into a JSON string, but with Objects, a quick advantage you get is the direct support to turn them into a JSON String using JSON.stringify(). Now, there are performance related differences too, but I'm going to cover them in a separate video using some benchmarking techniques, Thanks for watching, and be sure to subscribe if you haven't already. Until then, my friends keep learning and share your knowledge.