Map ad Set in JavaScript

 Map and Set

We've learned about the following complicated data structures up to this point:

Keyed collections are stored in objects.

For storing ordered collections, arrays are employed.

But in real life, that isn't enough.

Map

Like an Object, a Map is a collection of keyed data objects. The primary distinction is that Map accepts any type of key.

The following are examples of methods and properties:

  • new Map() is a function that generates a map.
  • The value is stored by the key in map.set(key, value).
  • map.get(key) – returns the value associated with the key, or null if the key does not exist on the map.

  • If the key exists, map.has(key) returns true; otherwise, it returns false.

  • map.delete(key) – deletes the value associated with the key.

  • map.clear() - clears the map of all items.

  • The current element count is returned by map.size.

One of the most noticeable and essential Map features is the use of objects as keys. The same cannot be said for Object. It's acceptable to use a String as a key in an Object, but we can't use another Object as a key in an Object.




Because visitsCountObj is an object, it transforms all Object keys, such as john and ben in the previous example, to the text "[object Object]." Certainly not what we desire.



Iteration Over Map
There are three techniques for looping around a map:
  • map.keys() produces a list of keys in an iterable.
  • map.values() produces a list of values in an iterable.
  • map.entries() – provides an iterable for [key, value] entries; it's used by default in for..of.








Comments

Popular posts from this blog

Array Methods in JavaScript for adding and removing items from the beginning and end of a list

The Complete Guide to Reacting for Beginners in 2021