JavaScript Hashmap: Performant Key-Value Variable
15 November, 2022
12
12
0
Contributors
What is a Map?
Map Methods & Property
Method | Description |
---|---|
set() | Sets the value for a key in a Map |
get() | Returns the value for a key |
has() | Returns a boolean indicating if a key exists in a Map |
delete() | Removes a key from a Map |
clear() | Removes all keys from a Map |
values() | Returns an iterator object of the values in a Map |
keys() | Returns an iterator object of the keys in a Map |
entries() | Returns an iterator object of the key-value pairs in a Map |
forEach() | Executes a provided function once for each key-value pair in a Map |
Property | Description |
---|---|
size | Returns the number of key/value pairs in a Map |
Map Example
Map Iteration
Map vs. Object
Map | Object |
---|---|
Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type. | Object keys must be either a string or a symbol. |
Map is iterable and can be easily looped over. | Object is not iterable and can not be easily looped over. |
Map has a built-in forEach method, so there is no need to convert it to an array. | Object does not have a built-in forEach method. |
Map has a size property, so we can easily get the number of items. | Object does not have a size property. |
Map can use objects as keys. | Object can not use objects as keys. |
Map is faster than Object in general. | Object is generally slower than Map. |
Conclusion
References
javascript
frontend
develevate
bestpractices
toolstipstricks