惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
A
About on SuperTechFans
博客园 - 【当耐特】
Microsoft Security Blog
Microsoft Security Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The GitHub Blog
The GitHub Blog
雷峰网
雷峰网
博客园_首页
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
IT之家
IT之家
博客园 - 叶小钗
Google DeepMind News
Google DeepMind News
aimingoo的专栏
aimingoo的专栏
博客园 - 聂微东
B
Blog RSS Feed
H
Help Net Security
Recent Announcements
Recent Announcements
阮一峰的网络日志
阮一峰的网络日志
D
DataBreaches.Net
L
LangChain Blog
Vercel News
Vercel News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Map and Set in JavaScript
Akash Kumar · 2026-06-26 · via DEV Community

"Objects and arrays are JavaScript's workhorses. Map and Set are their smarter siblings — built for the jobs where the workhorses struggle."


Introduction

JavaScript developers reach for objects and arrays instinctively — they're everywhere, they're familiar, and they handle most situations just fine. But both have real limitations that quietly cause bugs and unnecessary complexity.

What happens when you need an object whose keys aren't strings? What about storing a list of values where duplicates should be impossible? What if you need to know how many entries an object has without counting them yourself?

These are exactly the gaps that Map and Set were designed to fill. Introduced in ES6, they don't replace objects and arrays — they complement them. Knowing when to reach for each one is the mark of a developer who understands their tools.


1. What Is a Map?

A Map is a collection of key-value pairs where the keys can be any type — strings, numbers, objects, booleans, even functions. Every entry is unique by key, and the Map remembers the order entries were inserted.

Creating and Using a Map

const map = new Map();

// Setting entries — key can be ANY type
map.set("name", "Alice");       // string key
map.set(42, "the answer");      // number key
map.set(true, "boolean key");   // boolean key

const objKey = { id: 1 };
map.set(objKey, "object as key"); // object key — unique capability

// Getting values
console.log(map.get("name"));   // "Alice"
console.log(map.get(42));       // "the answer"
console.log(map.get(objKey));   // "object as key"

// Checking existence
console.log(map.has("name"));   // true
console.log(map.has("age"));    // false

// Size — instant, no counting needed
console.log(map.size);          // 4

// Deleting an entry
map.delete(42);
console.log(map.size);          // 3

Iterating a Map

Map preserves insertion order, making iteration predictable:

const userRoles = new Map([
  ["alice", "admin"],
  ["bob",   "editor"],
  ["carol", "viewer"]
]);

// Iterate entries in insertion order
for (const [user, role] of userRoles) {
  console.log(`${user}${role}`);
}
// alice → admin
// bob   → editor
// carol → viewer

// Access just keys or just values
console.log([...userRoles.keys()]);   // ["alice", "bob", "carol"]
console.log([...userRoles.values()]); // ["admin", "editor", "viewer"]

Map Initialization Shorthand

You can initialize a Map directly from an array of [key, value] pairs:

const scores = new Map([
  ["Alice", 98],
  ["Bob",   85],
  ["Carol", 91]
]);

console.log(scores.get("Alice")); // 98
console.log(scores.size);         // 3


2. What Is a Set?

A Set is a collection of unique values. Adding a value that already exists does nothing — the Set simply ignores it. Like Map, Set remembers insertion order.

Creating and Using a Set

const set = new Set();

set.add("apple");
set.add("banana");
set.add("cherry");
set.add("apple"); // duplicate — silently ignored

console.log(set.size);            // 3, not 4
console.log(set.has("banana"));   // true
console.log(set.has("mango"));    // false

set.delete("banana");
console.log(set.size);            // 2

The Uniqueness Property in Action

This is Set's defining characteristic. No matter how many times you add the same value, it appears exactly once:

const tags = new Set();

// Simulating tags being added from multiple places
tags.add("javascript");
tags.add("nodejs");
tags.add("javascript"); // already there — no-op
tags.add("webdev");
tags.add("nodejs");     // already there — no-op
tags.add("javascript"); // already there — no-op

console.log([...tags]); // ["javascript", "nodejs", "webdev"]
console.log(tags.size); // 3

SET UNIQUENESS — VALUES ARE STORED ONLY ONCE

Input stream:
  "js"  "css"  "js"  "html"  "css"  "js"  "html"
    ↓     ↓     ✗      ↓      ✗     ✗       ✗
  ┌─────────────────────────────────────────┐
  │  Set  │  "js"  │  "css"  │  "html"  │  │
  └─────────────────────────────────────────┘

Duplicates never enter. Set size stays at 3.

The Most Common Set Use Case: Deduplication

// Remove duplicates from an array — one line
const withDupes  = [1, 2, 3, 2, 4, 1, 5, 3];
const unique     = [...new Set(withDupes)];

console.log(unique); // [1, 2, 3, 4, 5]

// Works with strings too
const words    = ["the", "quick", "the", "brown", "fox", "the"];
const dedupedWords = [...new Set(words)];

console.log(dedupedWords); // ["the", "quick", "brown", "fox"]

Iterating a Set

const colors = new Set(["red", "green", "blue"]);

for (const color of colors) {
  console.log(color);
}
// red
// green
// blue

// Convert to array for array methods
const upperColors = [...colors].map(c => c.toUpperCase());
console.log(upperColors); // ["RED", "GREEN", "BLUE"]


3. Map vs. Object: When the Familiar Tool Falls Short

Objects look like key-value stores, and they work as one — until they don't. Here are the specific ways objects surprise you.

Problem 1: Object keys are always strings (or Symbols)

const obj = {};

// You set a number key...
obj[42] = "the answer";

// ...but it gets silently converted to a string
console.log(Object.keys(obj)); // ["42"] ← became a string

// This causes real bugs:
console.log(obj[42]);   // "the answer"
console.log(obj["42"]); // "the answer" — same thing!

// With Map, key types are preserved exactly:
const map = new Map();
map.set(42, "the answer");
map.set("42", "different value");

console.log(map.get(42));    // "the answer"
console.log(map.get("42")); // "different value" — genuinely separate

Problem 2: Objects have prototype baggage

const obj = {};

// These keys exist even though you never set them:
console.log("toString" in obj);        // true  ← inherited
console.log("hasOwnProperty" in obj);  // true  ← inherited
console.log("constructor" in obj);     // true  ← inherited

// This can cause unexpected bugs if your data has these key names
obj["toString"] = "my value"; // Silently shadows a built-in

// Map has zero inherited keys — completely clean slate:
const map = new Map();
console.log(map.has("toString"));        // false
console.log(map.has("hasOwnProperty"));  // false

Problem 3: No built-in size

const obj = { a: 1, b: 2, c: 3 };

// Getting the count requires a manual call:
console.log(Object.keys(obj).length); // 3 — workaround, not elegant

// Map has it built in:
const map = new Map([["a", 1], ["b", 2], ["c", 3]]);
console.log(map.size); // 3 — direct property

Side-by-Side Comparison

MAP vs. OBJECT
────────────────────────────────────────────────────────────────
Feature               │  Object             │  Map
──────────────────────┼─────────────────────┼──────────────────
Key types allowed     │  String, Symbol      │  Any type
Prototype keys        │  Yes (inherited)     │  None
Size                  │  Object.keys().length│  .size property
Insertion order       │  Not guaranteed *    │  Always preserved
Iteration             │  for...in, Object.keys│  for...of, .forEach
JSON serializable     │  Yes                 │  No (manual work)
Best for              │  Structured records  │  Dynamic key-value

* Modern engines do preserve string-key order, but it's not
  part of the spec for all cases (e.g. integer-like string keys).
────────────────────────────────────────────────────────────────


4. Set vs. Array: When Order Isn't the Point

Arrays are ordered lists that allow duplicates. Sets are unordered collections that guarantee uniqueness. The difference sounds small but changes everything.

Problem 1: Arrays don't enforce uniqueness

const subscribers = [];

function subscribe(email) {
  // Without a guard, duplicates slip in
  subscribers.push(email);
}

subscribe("alice@example.com");
subscribe("bob@example.com");
subscribe("alice@example.com"); // duplicate!

console.log(subscribers.length); // 3 ← should be 2
console.log(subscribers);
// ["alice@example.com", "bob@example.com", "alice@example.com"]

// With a Set — uniqueness is automatic:
const subscriberSet = new Set();

subscriberSet.add("alice@example.com");
subscriberSet.add("bob@example.com");
subscriberSet.add("alice@example.com"); // ignored

console.log(subscriberSet.size); // 2 ← correct

Problem 2: Checking membership in arrays is slow

const blocklist = ["spam1.com", "spam2.com", "spam3.com" /* ... 10,000 items */];

// Array .includes() scans every element — O(n) time
function isBlocked(domain) {
  return blocklist.includes(domain); // gets slower as list grows
}

// Set .has() uses a hash lookup — O(1) time regardless of size
const blocklistSet = new Set(["spam1.com", "spam2.com", "spam3.com"]);

function isBlockedFast(domain) {
  return blocklistSet.has(domain); // instant, 10 or 10,000 items
}

Problem 3: Removing duplicates from arrays is awkward

const ids = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3];

// Array approach — verbose
const uniqueIds = ids.filter((id, index) => ids.indexOf(id) === index);

// Set approach — clean one-liner
const uniqueIdsFast = [...new Set(ids)];

console.log(uniqueIdsFast); // [3, 1, 4, 5, 9, 2, 6]

Side-by-Side Comparison

SET vs. ARRAY
────────────────────────────────────────────────────────────────
Feature               │  Array              │  Set
──────────────────────┼─────────────────────┼──────────────────
Duplicates            │  Allowed            │  Not allowed
Access by index       │  Yes — arr[0]       │  No
Membership check      │  .includes() → O(n) │  .has()    → O(1)
Insertion order       │  Preserved          │  Preserved
Size                  │  .length            │  .size
Rich methods          │  .map .filter .reduce│  .add .has .delete
Deduplication         │  Manual / verbose   │  Automatic
Best for              │  Ordered sequences  │  Unique collections
────────────────────────────────────────────────────────────────


5. When to Use Map and Set

The right choice becomes clear once you know what property you need to enforce.

Reach for Map when:

Your keys aren't strings

// Storing metadata about DOM elements (object keys)
const elementData = new Map();
const button = document.querySelector("#submit");
elementData.set(button, { clicks: 0, lastClicked: null });

// Later — retrieve by the actual element reference
button.addEventListener("click", () => {
  const data = elementData.get(button);
  data.clicks++;
  data.lastClicked = new Date();
});

You need to count or tally things

const text = "the quick brown fox jumps over the lazy dog";
const wordCount = new Map();

for (const word of text.split(" ")) {
  wordCount.set(word, (wordCount.get(word) || 0) + 1);
}

console.log(wordCount.get("the")); // 2
console.log(wordCount.size);       // 8 unique words

You need to frequently check size or iterate in order

// Track active user sessions
const activeSessions = new Map();

activeSessions.set("user-001", { loginTime: Date.now(), ip: "192.168.1.1" });
activeSessions.set("user-002", { loginTime: Date.now(), ip: "10.0.0.5" });

console.log(`Active sessions: ${activeSessions.size}`);

for (const [userId, session] of activeSessions) {
  console.log(`${userId}: connected from ${session.ip}`);
}

Reach for Set when:

You need a list with guaranteed uniqueness

// Track which tutorial steps a user has completed
const completed = new Set();

completed.add("intro");
completed.add("setup");
completed.add("intro"); // already done — ignored

console.log(completed.has("setup")); // true
console.log(`${completed.size} of 5 steps done`);

You need fast membership checks

const SUPPORTED_CURRENCIES = new Set(["USD", "EUR", "GBP", "JPY", "INR"]);

function validateCurrency(code) {
  if (!SUPPORTED_CURRENCIES.has(code)) {
    throw new Error(`Unsupported currency: ${code}`);
  }
  return true;
}

You're working with set operations (union, intersection, difference)

const frontend = new Set(["alice", "bob", "carol"]);
const backend  = new Set(["carol", "dave", "eve"]);

// Union — everyone on either team
const allDevs = new Set([...frontend, ...backend]);
console.log([...allDevs]); // ["alice", "bob", "carol", "dave", "eve"]

// Intersection — works on both teams
const fullstack = new Set([...frontend].filter(dev => backend.has(dev)));
console.log([...fullstack]); // ["carol"]

// Difference — frontend only
const frontendOnly = new Set([...frontend].filter(dev => !backend.has(dev)));
console.log([...frontendOnly]); // ["alice", "bob"]

Decision Guide

Do you need key-value pairs?
  │
  ├─ YES → Do your keys need to be non-string types,
  │         OR do you need clean iteration / .size?
  │          ├─ YES → Use Map
  │          └─ NO  → Plain Object is fine
  │
  └─ NO → Do you need a list?
            ├─ YES → Must values be unique?
            │          ├─ YES → Use Set
            │          └─ NO  → Use Array
            └─ NO → You probably need neither


Quick Reference

Method / Property Map Set
Add an entry map.set(key, value) set.add(value)
Get a value map.get(key) — (no index access)
Check existence map.has(key) set.has(value)
Remove an entry map.delete(key) set.delete(value)
Count entries map.size set.size
Remove all map.clear() set.clear()
Iterate for (const [k, v] of map) for (const v of set)
Convert to array [...map] or [...map.values()] [...set]
Initialize from array new Map([[k1,v1],[k2,v2]]) new Set([v1,v2,v3])

Key Takeaways

  • Map is a key-value store where keys can be any type — not just strings
  • Set is a collection of unique values — duplicates are silently ignored on add
  • Use Map over Object when keys are non-strings, when you need .size, or when you want a clean prototype-free store
  • Use Set over Array when values must be unique, when you need fast O(1) membership checks with .has(), or when deduplicating
  • Both Map and Set preserve insertion order and are iterable with for...of
  • Convert between them and arrays easily with [...map], [...set], new Set(array), new Map(arrayOfPairs)

What's Next?

With Map and Set in your toolkit, great next topics include:

  • WeakMap and WeakSet — memory-efficient versions that allow garbage collection of keys; useful for caching and private data patterns
  • Iterators and generators — the protocol that makes Map and Set work with for...of
  • Array methods in depth.reduce(), .flatMap(), .find() — complementing what Set and Map don't do
  • Data structures in interviews — Map and Set are the foundation of solving many common algorithm problems efficiently

Objects and arrays will always be your everyday tools. Map and Set are the specialists — reach for them when the job calls for it, and your code will be cleaner and faster for it.


Next in the series: JavaScript's WeakMap and WeakSet — the memory-conscious cousins that clean up after themselves. 🚀