🔧 AI Nachrichten KI-Angriffe: Geheimdienste sollen neue Befugnisse erhalten(11.09.2026 um 11:00 Uhr)
🔧 AI Nachrichten Podcast: ChatGPT schwatzt Nutzern in Deutschland jetzt Werbung auf(28.08.2026 um 08:46 Uhr)
🐧 Linux TippsPACMAN: KI-Framework steuert Fusionsplasma in Echtzeit(11.09.2026 um 10:46 Uhr)
📰 IT NachrichtenAutismus und ADHS mit früher Weichmacher-Exposition verknüpft(12.09.2026 um 09:04 Uhr)
🪟 Windows TippsMicrosoft bringt Emoji 17.0 auf Windows 11(31.08.2026 um 08:16 Uhr)
⚠️ Malware / Trojaner / VirenNeue Android-Malware schreit Sie an, wenn Sie nicht zahlen(11.09.2026 um 10:33 Uhr)
📰 IT Nachrichten7-max: Tool bringt 10 bis 20 Prozent mehr Tempo für Programme(12.09.2026 um 09:30 Uhr)
⚠️ Malware / Trojaner / VirenHandy: Wer diese App installiert hat, sollte sein Gerät besser zurücksetzen(11.09.2026 um 16:55 Uhr)
🔧 AI Nachrichten KI-Angriffe: Geheimdienste sollen neue Befugnisse erhalten(11.09.2026 um 11:00 Uhr)
🔧 AI Nachrichten Podcast: ChatGPT schwatzt Nutzern in Deutschland jetzt Werbung auf(28.08.2026 um 08:46 Uhr)
🐧 Linux TippsPACMAN: KI-Framework steuert Fusionsplasma in Echtzeit(11.09.2026 um 10:46 Uhr)
📰 IT NachrichtenAutismus und ADHS mit früher Weichmacher-Exposition verknüpft(12.09.2026 um 09:04 Uhr)
🪟 Windows TippsMicrosoft bringt Emoji 17.0 auf Windows 11(31.08.2026 um 08:16 Uhr)
⚠️ Malware / Trojaner / VirenNeue Android-Malware schreit Sie an, wenn Sie nicht zahlen(11.09.2026 um 10:33 Uhr)
📰 IT Nachrichten7-max: Tool bringt 10 bis 20 Prozent mehr Tempo für Programme(12.09.2026 um 09:30 Uhr)
⚠️ Malware / Trojaner / VirenHandy: Wer diese App installiert hat, sollte sein Gerät besser zurücksetzen(11.09.2026 um 16:55 Uhr)

🔧 Programmierung 🕛 vor 2 Monaten 10 Min Lesezeit
0

Map and Set in JavaScript

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

"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






CODE
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:




CODE
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:




CODE
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






CODE
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:




CODE
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









CODE
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






CODE
// 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






CODE
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)






CODE
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






CODE
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






CODE
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






CODE
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






CODE
const subscribers = [];

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

subscribe("[email protected]");
subscribe("[email protected]");
subscribe("[email protected]"); // duplicate!

console.log(subscribers.length); // 3 ← should be 2
console.log(subscribers);
// ["[email protected]", "[email protected]", "[email protected]"]

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

subscriberSet.add("[email protected]");
subscriberSet.add("[email protected]");
subscriberSet.add("[email protected]"); // ignored

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









Problem 2: Checking membership in arrays is slow






CODE
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






CODE
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






CODE
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




CODE
// 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




CODE
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




CODE
// 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




CODE
// 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




CODE
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)




CODE
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






CODE
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. 🚀

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
1 Quelle
KI-Angriffe: Geheimdienste sollen neue Befugnisse erhalten
1 Quelle
Podcast: ChatGPT schwatzt Nutzern in Deutschland jetzt Werbung auf
1 Quelle
PACMAN: KI-Framework steuert Fusionsplasma in Echtzeit
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Map and Set in JavaScript

Thematisch verwandte Begriffe: JavaScript · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...