Cara menggunakan define map in javascript
Show Table of Contents
You may wonder — why Map vs Object but not Map vs Array, or Object vs Set? Well, you can also compare between any of the two, but Map and Object, unlike others, have very similar use-cases which require us to understand more deeply about them to decide what is better for when. And that’s what this is about. Let’s start, shall we? The conceptsWhat is Map?Map sounds very simple, doesn’t it? We see or hear about it almost everyday, let’s say World map, Street map, etc…. So what is exactly Map? Map is a data collection type (in a more fancy way — abstract data structure type), in which, data is stored in a form of pairs, which contains a unique key and value mapped to that key. And because of the uniqueness of each stored key, there is no duplicate pair stored. You may recognize by now one common thing about all examples mentioned above — they are used for looking up something (can be a country — for World map, a street name — Street map, etc…). That’s right, Map is mainly used for fast searching and looking up data. Example: {(1, “smile”), (2, “cry”), (42, “happy”)} in which each pair is in the format — (key, value). Important note: key and value in Map can be in any data type, not limited to only string or integer. And what about Object?Everyone knows Object, especially in Javascript. Object is object, isn’t it? Right, but not enough. Regular Object (pay attention to the word ‘regular’ ) in Javascript is dictionary type of data collection — which means it also follows key-value stored concept like Map. Each key in Object — or we normally call it “property” — is also unique and associated with a single value. In addition, Object in Javascript has built-in prototype. And don’t forget, nearly all objects in Javascript are instances of Object, including Map. Example: {1: ‘smile’, 2: ‘cry’, 42: ‘happy’} Therefore, by definition, Object and Map are based on the same concept — using key-value for storing data. However, like we always say — same same but different — they are indeed quite different from each other, mainly in:
var map = new Map([[1,2],[3,4]]); But not only those. What else makes them different from each other? Let us continue. How to constructObjectLike Array, Object is straight-forward. To declare new object, all you need to do is using direct literal: var obj = {}; //Empty object Or by constructor var obj = new Object(); //Empty Object Or by using Object.prototype.create var obj = Object.create(null); //Empty Object Special note: You only should use Object.create in very specific cases, such as:
var Vehicle = { In general, like in Array, do not use built-in constructor over literal in creating new object, because:
var obj = new Object(id: 1, name: "test") //Error - obviouslyvar obj1 = {id: 1, name: "test"}; And in any case, who wants to type extra unnecessary code — at all? MapMap, in the other hand, has only one way to create, by using its built-in constructor and new syntax. var map = new Map(); //Empty Map
The constructor receives an array or iterable object whose elements are key-value pairs — akaarrays with 2 elements [key, value]. So far so good? Great. Now it’s time to move on to our next step — comparison between Map/Object’s basic capabilities, which are: Accessing element
map.get(1)// 2
obj.id //1
map.has(1);//return boolean value: true/false
var isExist = obj.id === undefined; //check if obj has that property defined before.
isExist = 'id' in obj; //which will apply for inherited property as well. The syntax in Map is simpler and more direct than in Object in this case. Note: in Object, we have Object.prototype.hasOwnProperty() will return true/false to check if it has a specified key as its own property — it will be good in case we only check a key which is not inherited for that object. Still, to my opinion, here Map wins over Object regarding the ease of usage. Adding new element
map.set(4,5); //{1=>2, 2=>3, 4=>5}
map.set(4,6); //{1=>2, 2=>3, 4=>6}
obj['gender'] = 'female'; //{id: 1, name: "test", gender: "female"}
Removing/Deleting an elementIn Object, there is no built-in method to delete a property from it. Instead, we can use the operator delete as: delete obj.id; //{name: "test", gender: "male"} Pay attention that some may argue about whether it’s better to do the following instead, for performance boost. obj.id = undefined; However, the logic is quite different here:
Therefore, when we use “for…in…”, we still iterate over that property’s key regardless. And of course, the check for whether a key/property already exists in an obj will yield two different results in these two scenarios, except the following check: obj.id === undefined;//same result Hence, think carefully. Performance boost sometimes is not worth it! :) Oh one more thing, delete operator does return a string of “true”/ “false”, but unlike normal, this returned value indicates quite differently status, in which:
Meanwhile, Map, again, has few nice built-in methods to support different removing purposes, such as:
var isDeleteSucceeded = map.delete(1); //{ 2=>3, 4=>5}
map.clear(); //{}
In general, both Map and Object performance in removing element is pretty similar to each other, again due to its structure. Deleting a key will take O(1), while clearing out all elements will still take O(n) with n is the size of Map/Object. So, yeah, it’s definitely a tie here! Since we mentioned a bit about the size, let’s see how Map/Object behaves: Getting the sizeOne advantage here, which Map has in comparison to Object, is that Map does keep its size updated automatically, and we can always get the size easily by: console.log(map.size);//0 While with Object, it needs to be calculated manually, with the help of Object.keys() — which returns an array of all existing keys in a certain object: console.log(Object.keys(obj).length);//2 Got a hang of it? Great. Now the last comparison, as it marks one of the significant differences in Map and Object — iteration between elements. IteratingMap is built-in iterable — Object is not. Simple as that.
//typeof Which means, in Map all elements can be iterated directly with “for… of” as: //For map: { 2=>3, 4=>5} Or with its built-in forEach(): map.forEach((value, key) => console.log(`key: ${key}, value: ${value}`)); But with Object, either we use “for… in” {id: 1, name: "test"} Or using Object.keys(obj) to get all the keys and iterate: Object.keys(obj).forEach((key)=> console.log(`key: ${key}, value: ${obj[key]}`)); OK, here comes the question — since they are really similar to each other in both structure and performance wise, with Map having slightly more advantages compared to Object, should we always prefer Map over Object? When to use Map? And when to use Object?Again, despite all the advantages Map can have against Object, there is still cases Object will perform better. After all, Object is the most basic concept of Javascript.
var obj = { (Try to do it the same with Map. You just can’t!)
ConclusionIn conclusion, it really depends on what kind of data (input) you are going to work with and what operations you are going to perform on them in order to prefer one to the other between Map and Object. Map tends to have more advantages over Object in scenarios when we just need a simple look-up structure for data storing, with all the basic operations it provided. However, Map can’t never replace Object, in any sense, because in Javascript, Object is — after all — more than just a normal hash table (and therefore shouldn’t be used as a normal hash table if there is alternative, it’s just a waste of a great resource ;)). Now honestly, which one you like better? :). Tell me in comments. I’d love to know your opinion. |