DEV Community

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

Posted 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.

Why Objects are Not Enough

JavaScript offers us two “collection”-like objects—objects (represented via the {} literal) and arrays (represented using the [] literal).

Objects, often referred to as associative arrays, or dictionaries provide lookup via keys.
Arrays on the other hand provide a sequential data-structure that provide efficient random lookup via indexes.
Objects and arrays, while useful, do not prove to be sufficient for all use-cases.
One *limitation * of objects serving as a true key-value store is that object keys are strings.

In other words, the “type” of the key is not retained when used in an object. This can be trivially demonstrated:
const obj1 = {
'true': 'String',
true: 'Boolean',
}; ①
console.assert(obj1[true] === 'Boolean'); ②
const obj2 = {
true: 'Boolean',
'true': 'String',
}; ③
console.assert(obj2[true] === 'String'); ④

① Create an object with two seemingly different keys
② Interrogate the object for a key with a type
③ Swap the order of key value pairs with no other change
④ The same lookup is now different

Lets start by exploring maps, followed by sets.

Top comments (0)