Do you know these data-types in JavaScript

Besides all the known data types in javascript like Stings, Arrays, and Objects, there are some other types that are not widely used.

In this article, I will explain Two data types in JS

  • Maps
  • Sets

Maps

Maps are collections of key-value items, and yes this is similar to Objects.
However, there are some differences that make the Maps data type unique 😎 .

  • Objects Keys are always one of type String or Symbol, you can not have a key in an object with any other type
  • Maps Keys can be any type of data

Let's see some examples for object keys
Alt Text

As we can see in the above example, objects keys are converted to type string even if they are not strings
so the keys are converted like this

  • 1 will be '1'
  • 'string' will be 'string'
  • {'key':'value'} will be [object Object] which is the output from conversion of object to a string

Now let's see how the Maps types handle this issue
Alt Text

as we can see the keys of the Map remain the same without any conversion in type.

In the below table, there is a comparison between Map and Object

Maps Objects
Keys Can be any data type Any key should be of type string or symbol
Define let map = new Map(); let obj = {}
Set pair (key-value) map.set(key,value) obj[key] = value
get value of key map.get(key) obj[key]
remove value by key map.delete(key) obj[key]=undefined
get keys map.keys()
returns an iterable for keys
Object.keys(obj)
check if has key map.has(key) obj.hasOwnProperty(key)

Sets

Sets is another data type in JS, it is a collection of values where each value occur only once.

Let's see an example
Alt Text

An interesting application for this is to remove the duplicate values from array. For example
Alt Text

You can know more about Maps and Sets from here 🌻

Finally, it is great to know more about all the types of Javascript as you can need them in the future.
even if you rarely use them, having the knowledge of these types will expand your ability to have different solutions for some problems πŸŽ‰

22