JavaScript Set Object

Subject: JavaScript

The Set object in JavaScript is a collection of unique values, meaning duplicates are automatically ignored. It is useful for storing distinct values and performing operations such as filtering duplicates, checking if a value exists, and implementing set-based logic (like unions and intersections).

Unlike arrays, Sets ensure all values are unique and maintain the insertion order. They accept any data type including strings, numbers, and objects.


Key Features of JavaScript Set

  • Stores only unique values.
  • Maintains insertion order.
  • Accepts any data type (strings, numbers, objects, etc.).
  • Provides built-in methods like .add(), .delete(), .has(), and .clear().

Creating a Set

Adding Values

Initialize with Values


Common Set Methods

  • .add(value): Adds a new element.
  • .delete(value): Removes an element.
  • .has(value): Checks for existence.
  • .clear(): Removes all elements.
  • .size: Returns the number of elements.

Example: Removing Duplicates from an Array


Iterating Over a Set


Working with Objects in a Set


Converting Set to Array


Key Takeaways

  • Set stores unique values only.
  • Supports any data type, including objects and functions.
  • Automatically ignores duplicates.
  • Convert to array using spread syntax [...set] or Array.from(set).
  • Use Set for efficient lookups, removing duplicates, and tracking unique items.
Next : Use of Set