DEV Community

Cover image for Maps and Sets in JavaScript
M.Ark
M.Ark

Posted on • Edited on

Maps and Sets in JavaScript

A programming language must provide us with all of the necessary constructs that empower developers to model their domain and problem space clearly and efficiently.
Till date, JavaScript lacked support for two fundamental types that most other languages offer, namely maps and sets.

The Limitations of Objects

JavaScript provides objects (created with {}) and arrays ([]) for collections. Objects, often likened to associative arrays or dictionaries, allow lookup by keys, while arrays offer efficient random access via indexes. However, these structures have limitations.
One significant limitation is that object keys are always coerced to strings. This means that the type of the key is not preserved when used in an object, which can lead to unexpected behavior. Consider this code:

Image description

Here, despite having seemingly different keys ('true' and true), the lookup retrieves the value associated with the boolean key.

This is due to JavaScript coercing both keys to strings.

Swapping the order of key-value pairs further demonstrates this:

Image description

In this case, the lookup now retrieves the value associated with the string key 'true'.

Lets start by exploring maps, followed by sets.

Top comments (0)