Javascript

What is new Set(); in JavaScript

In JavaScript,

new Set();

creates a Set object, which is a built-in collection type that stores unique values — meaning no duplicates are allowed.


Key points about a Set in JS

  • No duplicate values — if you try to add a duplicate, it’s ignored.
  • Can store any type of value — numbers, strings, objects, etc.
  • Keeps values in insertion order (but there’s no index like an array).
  • Has its own methods for adding, checking, and deleting values.

Example

const mySet = new Set();

// Add values
mySet.add(1);
mySet.add(2);
mySet.add(2); // duplicate, ignored
mySet.add("hello");
mySet.add({ name: "Varun" });

console.log(mySet); // Set(3) { 1, 2, 'hello', { name: 'Varun' } }

// Check if value exists
console.log(mySet.has(2)); // true

// Delete a value
mySet.delete(1);

// Size of set
console.log(mySet.size); // 3

// Loop through set
for (let value of mySet) {
  console.log(value);
}

Common Use Cases

  • Removing duplicates from arrays:
const numbers = [1, 2, 2, 3, 4, 4];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4]
  • Tracking visited items in algorithms.
  • Storing unique IDs in an application.

Leave a Reply

Your email address will not be published. Required fields are marked *