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

推荐订阅源

D
Docker
AI
AI
博客园 - 三生石上(FineUI控件)
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Y
Y Combinator Blog
大猫的无限游戏
大猫的无限游戏
H
Hackread – Cybersecurity News, Data Breaches, AI and More
雷峰网
雷峰网
NISL@THU
NISL@THU
S
Schneier on Security
T
Threatpost
T
Tenable Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
IT之家
IT之家
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
C
Cybersecurity and Infrastructure Security Agency CISA
P
Privacy & Cybersecurity Law Blog
I
Intezer
Microsoft Azure Blog
Microsoft Azure Blog
月光博客
月光博客
T
Threat Research - Cisco Blogs
SecWiki News
SecWiki News
AWS News Blog
AWS News Blog
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
V
V2EX
Recorded Future
Recorded Future
Microsoft Security Blog
Microsoft Security Blog
S
Secure Thoughts
Google DeepMind News
Google DeepMind News
MongoDB | Blog
MongoDB | Blog
Apple Machine Learning Research
Apple Machine Learning Research
Project Zero
Project Zero
PCI Perspectives
PCI Perspectives
G
GRAHAM CLULEY
Help Net Security
Help Net Security
Cloudbric
Cloudbric
Recent Announcements
Recent Announcements
V
Visual Studio Blog
Hacker News: Ask HN
Hacker News: Ask HN
N
News and Events Feed by Topic
C
CERT Recently Published Vulnerability Notes
The Cloudflare Blog
Forbes - Security
Forbes - Security
C
Cisco Blogs
O
OpenAI News
www.infosecurity-magazine.com
www.infosecurity-magazine.com

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
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. 🚀