JavaScript Set & Map Objects Kya Hote Hai?
Collections aur key-value data ko manage karne ke liye in modern data structures ko samjhein.
1. Set Object
JavaScript mein Set ek special collection hai jo sirf unique values ko hi store karta hai. Iska matlab hai ki agar aap ek hi value ko Set mein baar-baar add karne ki koshish karenge, to woh sirf ek hi baar store hogi.
Key Features of Set:
- Unique Values Only: Duplicate values automatically ignore ho jaate hain.
- Any Data Type: Aap isme primitive values (string, number) aur objects dono store kar sakte hain.
- Iterable: Aap ispar
for...of
loop yaforEach()
method ka use kar sakte hain.
let mySet = new Set();
mySet.add(10);
mySet.add(20);
mySet.add(10); // Yeh duplicate hai, isliye ignore ho jayega
console.log(mySet); // Output: Set(2) { 10, 20 }
// Array se duplicate hatana
const numbers = [1, 2, 2, 3, 4, 3];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4]
2. Map Object
JavaScript ka Map object key-value pairs ko store karta hai. Yeh plain JavaScript object { }
se zyada powerful aur flexible hai kyunki isme keys kisi bhi data type (object, function, etc.) ki ho sakti hain, jabki plain objects me keys sirf strings ya symbols ho sakti hain.
Key Features of Map:
- Any Type of Keys: Keys numbers, strings, objects, ya functions bhi ho sakti hain.
- Insertion Order: Map keys ka insertion order yaad rakhta hai.
- Better Performance: Frequent additions aur deletions ke liye yeh plain objects se zyada efficient hai.
let myMap = new Map();
let keyString = 'a string';
let keyObj = {};
let keyFunc = function() {};
// keys set karna
myMap.set(keyString, "Value for a string");
myMap.set(keyObj, "Value for an object");
myMap.set(keyFunc, "Value for a function");
console.log(myMap.get(keyString)); // "Value for a string"
console.log(myMap.size); // 3
Set vs. Map: Quick Comparison
Feature | Set | Map |
---|---|---|
Structure | Sirf unique values | Key-value pairs |
Purpose | Unique items ka collection banana. | Data ko key ke saath associate karna. |
Key Type | N/A | Any data type |
Primary Use Case | Array se duplicates hatana. | Complex key-value data store karna. |
Test Your Knowledge!
Kya aap Set & Map ke baare mein seekh chuke hain? Chaliye dekhte hain!
Start Quiz