Knowledgize

Set Object

The Set object in JavaScript is a collection of unique values, meaning a value can only occur once in a Set. It maintains the order of insertion and allows for any type of value, whether primitive or object references.


  • Creation: const set = new Set(); creates an empty set.
  • Adding Values: set.add(value); adds a new value to the set.
  • Checking Existence: set.has(value); returns true if the value exists in the set.
  • Removing Values: set.delete(value); removes the value from the set.
  • Size: set.size; returns the number of values in the set.
  • Iteration: The Set object can be iterated over using methods like forEach, or using for...of loops on set.keys(), set.values(), and set.entries().


Example Usage


const set = new Set(); set.add('apple'); set.add('banana'); set.add('apple'); // Duplicate, will not be added console.log(set.has('apple')); // Output: true console.log(set.size); // Output: 2 set.delete('banana'); console.log(set.size); // Output: 1 set.forEach(value => { console.log(value); }); // Output: // apple


Additional Information


  1. Maintaining Order:

    • Sets maintain the order of insertion, which makes iteration predictable.
  2. Value Types:

    • Values in a Set can be of any type, including objects, functions, and primitives.
  3. Iteration:

    • You can iterate over the values in a Set using methods like for...of with set.values() or set.keys() (which are identical in sets).