Skip to content

Instantly share code, notes, and snippets.

@naterexw
Last active April 6, 2018 04:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naterexw/2627e2197f5f3cf4acbab798e65cc0cf to your computer and use it in GitHub Desktop.
Save naterexw/2627e2197f5f3cf4acbab798e65cc0cf to your computer and use it in GitHub Desktop.
# Map vs Object
| 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)](https://jsperf.com/es6-map-vs-object-properties/2) | If all keys are strings, and you just use get and set, Objects are more performant. |
# Map vs WeakMap
| 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 vs Array
| 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 vs WeakSet
| 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|
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment