ES6: Set – WeakSet & Map – WeakMap

In the realm of modern JavaScript, ES6 (ECMAScript 2015) introduced several new data structures to the language, greatly enhancing its capabilities. Two key additions are Sets and Maps, along with their weak counterparts, WeakSets and WeakMaps. Understanding these data structures and their differences is crucial for efficient and robust JavaScript programming. Let’s delve into each of them.

Sets: Unique Value Collections

A Set in JavaScript is a collection of unique values, which can be of any type, whether primitive or object references. Sets do not allow duplicate values, ensuring each element appears only once within the collection.

Purpose:

Store unique values, preventing duplicates. Ideal for scenarios where order doesn’t matter (e.g., keeping track of unique user IDs, or removing duplicates from an array).

Key Methods:

  • add(value): Adds a value to the Set. Returns the Set itself.
  • has(value): Checks if a value exists in the Set. Returns true or false.
  • delete(value): Removes a value from the Set. Returns true if successful, false otherwise.
  • size: Returns the number of elements in the Set.
  • clear(): Removes all elements from the Set.
  • values(): Returns an iterator object containing the Set’s values.

Syntax:

let mySet = new Set();

Example:

// Creating a set
let mySet = new Set();
// Adding elements to the set
mySet.add(1);
mySet.add("Hello");
mySet.add({ key: "value" });
// Checking the size of the set
console.log(mySet.size); // Output: 3
// Adding duplicate values (ignored)
mySet.add(1);
// Iterating over the set
mySet.forEach(item => {
    console.log(item);
});
// Output:
// 1
// Hello
// { key: "value" }
// Checking for existence
console.log(mySet.has(1)); // Output: true
// Deleting an element
mySet.delete("Hello");
// Clearing the entire set
mySet.clear();

WeakSets: Keeping Track of Objects with a Light Touch

Purpose: Stores objects only, and the references are weak, meaning the objects can be garbage collected even if they’re in the WeakSet.

Key Methods:

  • add(value): Adds an object to the WeakSet.
  • has(value): Checks if an object exists in the WeakSet.
  • delete(value): Removes an object from the WeakSet (returns true if successful).
  • Important Note: WeakSets don’t have methods like size, clear(), values(), or forEach() because iteration wouldn’t be reliable due to weak references.

Syntax:

const myWeakSet = new WeakSet();

Example:

let myWeakSet = new WeakSet();
let obj = { name: "John" };
// Adding object to WeakSet
myWeakSet.add(obj);
// Checking for existence
console.log(myWeakSet.has(obj)); // Output: true
// Removing the object reference
obj = null;
// Now, the object may be garbage collected, and WeakSet will automatically remove it.

Things to remember with WeakSets:

Due to weak references, methods like size, has, and delete are not directly available on WeakSets.

WeakSets are primarily used for internal data structures or private member management within objects.

Maps: Key-Value Pairs on Steroids

Maps are like enhanced objects that store key-value pairs. However, unlike objects, keys in Maps can be of any data type, not just strings. This provides greater flexibility for data organization.

Purpose:

Stores key-value pairs where keys can be of any data type (primitives or objects). Values can be any data type as well.

Key Methods:

  • set(key, value): Sets a key-value pair in the map.
  • get(key): Retrieves the value associated with a key.
  • has(key): Checks if a key exists in the map.
  • delete(key): Removes a key-value pair from the map (returns true if successful).
  • size: Returns the number of key-value pairs in the map.
  • clear(): Removes all key-value pairs from the map.
  • keys(): Returns an iterator for the keys in the map.
  • values(): Returns an iterator for the values in the map.
  • entries(): Returns an iterator for key-value pairs as [key, value] arrays.
  • forEach(callback): Executes a function for each key-value pair in the map.

Syntax:

let myMap = new Map();

Example:

const personMap = new Map();
personMap.set("name", "Alice");
personMap.set(30, "age"); // Keys can be numbers
console.log(personMap.get("name")); // Output: "Alice"
console.log(personMap.has(30)); // Output: true
personMap.delete("age");
console.log(personMap); // Output: Map(1) {"name" => "Alice"}

WeakMaps: Like Maps, But Lighter on Their Feet

WeakMaps resemble Maps in their key-value storage functionality. However, similar to WeakSets, WeakMaps hold weak references to objects as keys. This implies that the objects themselves are not prevented from garbage collection even if they’re used as keys in the WeakMap.

Syntax:

Syntax:
let myWeakMap = new WeakMap();

Example:

let myWeakMap = new WeakMap();
let keyObject = { id: 1 };
let valueObject = { data: "some data" };
// Adding a key-value pair
myWeakMap.set(keyObject, valueObject);
// Retrieving the value by key
console.log(myWeakMap.get(keyObject)); // Output: { data: "some data" }
// Removing the key reference
keyObject = null;
// Now, the key object may be garbage collected, and WeakMap will automatically remove the corresponding entry.

Explanation:

Similar to WeakSet, WeakMap is a collection of key-value pairs where the keys must be objects and are weakly referenced. If there are no other references to a key stored in a WeakMap, it may be garbage collected.

WeakMaps are advantageous when you need to associate additional data with objects without preventing those objects from being garbage collected when they’re no longer needed.

Conclusion:

Understanding Sets, WeakSets, Maps, and WeakMaps in JavaScript is essential for effective data management and memory optimization in your applications. Sets and Maps provide powerful tools for managing collections of data, while WeakSets and WeakMaps offer additional flexibility when dealing

Leave a Reply

© 2023 Code Cloud Cafe ® All Rights Reserved.