| Map | Object |
|---|---|
| Map is introduces in ES6. | Objects were there since the birth of JS. |
| Accepts anything (even NaN) as key. | The keys can only be String or Symbol. |
.set() and .get() functions are used. | Assign values with = operator. |
Is an iterable and forEach & for of can be used. | Not an iterable. You can not use myObj.forEach() etc. |
.size property of a map shows the size. | You can not get size of an object easily. |
Map is a map. You can even do myMap.set("set", "will not change set"). | As objects has prototypes, key conflicts may occur. |
Map has .clear() to clear everything. | To clear properties, you need to write manual code. |
| If you focus on iterating, map will be more performant. (TEST) | If all keys are strings, and you just use get and set, Objects are more performant. |
| Map | WeakMap |
|---|---|
| Key in Map can be anything. | Key in WeakMap must be of type Object (not null). |
To find number of elements use .size | To find elements count use .length |
.forEach() is available to iterate | No .forEach() to iterate |
| Nothing is auto destroyed | If a key object is deleted, the value assigned against that key in any WeakMap will also be destroyed. |
| Set | Array |
|---|---|
| Contains only unique values | Contains whatever value you push |
| Focused to value. You can delete a value easily | Focused to index. You need to write code to find and delete a particular element |
.add() to add an element | .push() to add an element |
.has() to find if an element is there in a set | .includes() (ES7) to find if an element is there in an array |
.size to find number of elements | .length to find how many elements |
.mySet.clear() to clear a Set | arrr.spice(0, arr.length) to empty an array |
| Set | WeakSet |
|---|---|
| Can contain any type of values | Can only contain objects |
To find number of elements use .size | To find elements count use .length |
.forEach() is available to iterate | No .forEach() to iterate |
| Nothing is auto destroyed | If an element object has no other reference left, it will be auto released to garbage collector |