naterexw
4/6/2018 - 4:06 AM

Set <-> Array, Map <-> Object comparison

Map vs Object

MapObject
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 vs WeakMap

MapWeakMap
Key in Map can be anything.Key in WeakMap must be of type Object (not null).
To find number of elements use .sizeTo find elements count use .length
.forEach() is available to iterateNo .forEach() to iterate
Nothing is auto destroyedIf a key object is deleted, the value assigned against that key in any WeakMap will also be destroyed.

Set vs Array

SetArray
Contains only unique valuesContains whatever value you push
Focused to value. You can delete a value easilyFocused 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 Setarrr.spice(0, arr.length) to empty an array

Set vs WeakSet

SetWeakSet
Can contain any type of valuesCan only contain objects
To find number of elements use .sizeTo find elements count use .length
.forEach() is available to iterateNo .forEach() to iterate
Nothing is auto destroyedIf an element object has no other reference left, it will be auto released to garbage collector