Skip to main content

Working with Data

Maps and Sets

0:00
LearnStep 1/3

Beyond Arrays and Objects

JavaScript ES6 introduced Map and Set to handle collection use cases that standard Objects and Arrays address inefficiently or clumsily.

The Map Object

While Objects are historically used for key-value pairs, they have limitations: keys must be strings or symbols, they have a prototype chain, and iterating them requires helper methods like Object.keys(). A Map allows keys of any type (including objects and functions), maintains insertion order, and has a size property.

javascript

The Set Object

A Set is a collection of unique values. It mimics the mathematical concept of a set. It is ideal for removing duplicates from arrays or checking for the existence of a value efficiently (O(1) time complexity on average).

javascript

WeakMap and WeakSet

JavaScript also provides WeakMap and WeakSet. These hold weak references to objects, meaning if the object is garbage collected, it is automatically removed from the collection. They are not iterable but are crucial for preventing memory leaks when associating metadata with objects.