How to Use Maps, Sets, WeakSets, and WeakMaps in Object-Oriented JavaScript?

Estimated read time 2 min read
  1. Maps in JavaScript: Maps are data structures that store key-value pairs and allow you to efficiently look up values based on their keys.

Example of using a Map:

const map = new Map();
map.set("name", "John Doe");
map.set("age", 30);
console.log(map.get("name")); // John Doe
console.log(map.get("age")); // 30
  1. Sets in JavaScript: Sets are data structures that store unique values and do not allow duplicates.

Example of using a Set:

const set = new Set();
set.add(1);
set.add(2);
set.add(1);
console.log(set.size); // 2
  1. WeakSets in JavaScript: WeakSets are similar to Sets, but the values in a WeakSet can be garbage collected if they are not referenced anywhere else in your code.

Example of using a WeakSet:

const weakSet = new WeakSet();
const object1 = {};
const object2 = {};
weakSet.add(object1);
weakSet.add(object2);
console.log(weakSet.has(object1)); // true
  1. WeakMaps in JavaScript: WeakMaps are similar to Maps, but the keys in a WeakMap can be garbage collected if they are not referenced anywhere else in your code.

Example of using a WeakMap:

const weakMap = new WeakMap();
const object1 = {};
const object2 = {};
weakMap.set(object1, "Object 1");
weakMap.set(object2, "Object 2");
console.log(weakMap.get(object1)); // Object 1

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply