Skip to main content

Command Palette

Search for a command to run...

Map and Set in JavaScript

Updated
6 min read
Map and Set in JavaScript

Introduction

If you’ve worked with JavaScript, you’re likely familiar with objects and arrays.

Object stores key-value pairs, and it has some built-in methods that allow us to perform operations on it.

Same with array, it is basically used to store ordered data. It can store numbers, strings, functions, objects and array itself at the same time in a single variable. It also has many built-in functions to manipulate and perform operations on it.

But there are some drawbacks of these two, let’s start with object.

Problem with Object

In object we store key-value pairs, and keys are limited to strings or symbols, which is not efficient in some special use cases. That is where Map comes into the picture.

Problem with Array

Array stores ordered collection of data which is fine, but it can store multiple duplicates of the same value. There is no uniqueness in this, so that is where Set comes into the picture.


What Map is?

Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

In Map, keys can be strings, numbers, objects, functions, arrays, etc., which makes it useful for special use cases where different key types are required.

To create a map, we use the Map() function with the new keyword.

const map = new Map();

It has many built in function to perform operations

Methods and properties are:

const map = new Map();

// Different key types
map.set("name", "Kaneki");       // string
map.set(1, "one");               // number
map.set(true, "boolean");        // boolean
map.set({ id: 1 }, "object");    // object

// Access
console.log(map.get("name"));
console.log(map.get(1));
console.log(map.get(true));

What Set is?

Set stores an ordered collection of values, similar to an array, but all elements are unique.

To initialize a set, we use the Set() method with the new keyword.

let set = new Set();

Set also have built in methods:

Its main methods are:

  • new Set([iterable]) – creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.

  • set.add(value) – adds a value, returns the set itself.

  • set.delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false.

  • set.has(value) – returns true if the value exists in the set, otherwise false.

  • set.clear() – removes everything from the set.

  • set.size – is the elements count.

const set = new Set();

// Different data types
set.add("hello");        // string
set.add(1);              // number
set.add(true);           // boolean
set.add({ id: 1 });      // object
set.add(() => {});       // function

console.log(set.has(1));

console.log(set.size);

set.delete(true);

set.clear();

The main feature is that repeated calls of set.add(value) with the same value don’t do anything. That’s the reason why each value appears in a Set only once.


Difference Between Map and Object

Feature Map Object
Key Types Any (object, function, primitive) String & Symbol only
Order Preserves insertion order Mostly insertion (not strict)
Iteration Direct (for...of) Use Object.entries()
Size map.size Object.keys(obj).length
Performance Better for frequent ops Better for static data
Default Keys No prototype keys Has prototype (__proto__)
Use Case Dynamic key-value store Simple structured data

Difference Between Set and Array

Feature Set Array
Values Unique only (no duplicates) Allows duplicates
Order Insertion order Indexed order
Access No index access Index-based (arr[i])
Methods add, delete, has push, pop, map, etc.
Search Faster (has) Slower (includes)
Size set.size array.length
Use Case Unique collection Ordered list / sequences

When to Use Map and Set?

Map

In JavaScript, you should use the Map data structure when you need a robust, high-performance key-value store that goes beyond the capabilities of a standard Object

  • Non-String Keys: Unlike objects, which convert all keys to strings or symbols, a Map allows any data type including function, obejct and primitives to be used as a key.

  • Frequent Modifications: Map is specifically optimized for scenarios involving frequent additions and removals of key-value pairs.

  • Guaranteed Insertion Order: A Map strictly remembers the original insertion order of its elements, ensuring that iteration occurs in the same sequence every time.

  • Large Datasets: For massive datasets (often in the millions of entries), Map generally offers better memory efficiency and faster performance than objects.

Set

You should use the Set data structure in JavaScript when your primary goals are ensuring uniqueness and fast membership testing.

The most common scenarios for using a Set include:

  • Removing Duplicates from Arrays: Converting an array to a Set and back to an array is the standard "one-liner" for deduplication.

    const arr = [1, 2, 2, 3, 4, 4];
    const unique = [...new Set(arr)];
    
    console.log(unique); // [1, 2, 3, 4]
    
  • Frequent Membership Checks: Use .has() if you need to repeatedly check if an item exists in a large collection. Sets use hash tables internally, making this operation O(n) (constant time), whereas an array's .includes() is O(n) (linear time).

  • Mathematical Set Operations: Use Sets when you need to perform operations such as Union (combining lists), Intersection (finding common items), or Difference (finding items in one list but not the other).


Conclusion

Map and Set were not part of JavaScript from the beginning; they were introduced in ES6 to solve the problems discussed in this blog.

They are more optimized and can offer better performance, but use them wisely. If your use case can be fulfilled with regular objects and arrays, then prefer those.

That was all about Map and Set data types.

Hope you like this blog❤️.