Featured
- Get link
- X
- Other Apps
π§ Day 32 — Maps, Sets, WeakMaps & WeakSets
π§ Day 32 — Maps, Sets, WeakMaps & WeakSets
Hi Guys Welcome to Day 32 π You’ve learned modern JavaScript syntax — now let’s explore modern **data structures**. While objects and arrays work fine for most cases, ES6 introduced **Map**, **Set**, **WeakMap**, and **WeakSet** for better performance and control over memory.
π 1️⃣ Map — Key-Value Pairs (Better than Objects)
Unlike objects, Map allows any type of key — even objects or functions.
let userAge = new Map();
userAge.set("Rahul", 22);
userAge.set("Aisha", 25);
console.log(userAge.get("Rahul")); // 22
console.log(userAge.size); // 2
userAge.delete("Aisha");
console.log(userAge.has("Aisha")); // false
π§© 2️⃣ Iterating Through Maps
for (let [key, value] of userAge) {
console.log(`${key} is ${value} years old.`);
}
Maps maintain insertion order and are faster for large collections.
π 3️⃣ Set — Store Unique Values
A Set stores only unique values. Duplicates are automatically removed.
let fruits = new Set(["apple", "banana", "apple"]);
console.log(fruits); // Set(2) { 'apple', 'banana' }
fruits.add("orange");
fruits.delete("banana");
console.log(fruits.has("orange")); // true
π§ 4️⃣ Convert Between Set & Array
let arr = [1,2,2,3,3,4]; let unique = [...new Set(arr)]; console.log(unique); // [1,2,3,4]
⚙️ 5️⃣ WeakMap — Lightweight Map for Objects
A WeakMap is similar to Map, but it only accepts objects as keys and does not prevent garbage collection.
let weakMap = new WeakMap();
let obj = {};
weakMap.set(obj, "Sensitive Data");
console.log(weakMap.get(obj));
obj = null; // object is removed from memory automatically
π§© 6️⃣ WeakSet — For Object References Only
let weakSet = new WeakSet();
let person = { name: "Rahul" };
weakSet.add(person);
console.log(weakSet.has(person)); // true
person = null; // automatically cleaned up
π‘ 7️⃣ When to Use What
- Map → Store key-value pairs with any type of key.
- Set → Store unique values efficiently.
- WeakMap → Store temporary object-keyed data.
- WeakSet → Track object references without memory leaks.
π― Summary
Maps and Sets are faster and more memory-efficient than traditional objects and arrays for certain tasks. WeakMaps and WeakSets help manage memory automatically by allowing garbage collection — a key for optimizing apps. Tomorrow you’ll dive into one of the most powerful JavaScript concepts — Closures and Scope.
Popular Posts
π Day 27: Bootstrap Mini Project – Responsive Portfolio Page
- Get link
- X
- Other Apps
π¨ Day 2: Headings, Paragraphs & Text Formatting
- Get link
- X
- Other Apps
Comments
Post a Comment