JavaScript

Last Updated: 2/2/2023

Sets

  • A JavaScript Set is a collection of unique values.
  • Each value can only occur once in a Set.
// Create a Set
const letters = new Set();

// Add Values to the Set
letters.add("a");
letters.add("b");
letters.add("c");

letters.forEach (function(value) {  
	console.log(value);  
})
for (const x of letters.values()) {  
	console.log(x);  
}

Important Methods

  • size: Returns the number of elements in a Set
  • add: Adds a new element to the Set
  • delete: Removes an element from a Set
  • has: Returns true if a value exists in the Set
  • forEach: Invokes a callback for each element in the Set
  • values: Returns an iterator with all the values in a Set

WeakSet

  • You can only add objects to WeakSet (not primitives).
  • If there are no other references to the object in weakset, it will be removed from memory and from the weakset automatically.
  • It supports add, has and delete, but not size, keys() and no iterations.
let users = new WeakSet();
let user1 = {name: "ganesh"};
users.add(user1);
let user2 = {name: "siva"};
users.add(user2);

user2 = null;