Exercise

A Set is a built-in JavaScript object that stores a collection of unique values. Unlike arrays, a Set does not allow duplicate entries. You can create an empty Set using the new Set() constructor.

javascript

// Creating an empty Set
const mySet = new Set();

console.log(mySet); // Set(0) {}
console.log(typeof mySet); // "object"
console.log(mySet instanceof Set); // true

You can create a Set with initial values by passing an iterable (such as an array) to the Set() constructor. Each value in the iterable is added to the Set, and any duplicates are automatically removed.

javascript

// Creating a Set with initial values
const fruits = new Set(['apple', 'banana', 'cherry']);

console.log(fruits); // Set(3) { 'apple', 'banana', 'cherry' }
console.log(fruits.size); // 3

// Duplicates are removed automatically
const numbers = new Set([1, 2, 3, 2, 1]);
console.log(numbers); // Set(3) { 1, 2, 3 }

Use the .add() method to insert a new value into a Set. The .add() method returns the Set itself, so you can chain multiple .add() calls together.

javascript

const colors = new Set();

// Adding elements one by one
colors.add('red');
colors.add('green');
colors.add('blue');

console.log(colors); // Set(3) { 'red', 'green', 'blue' }

// Chaining .add() calls
const pets = new Set();
pets.add('cat').add('dog').add('fish');

console.log(pets); // Set(3) { 'cat', 'dog', 'fish' }

When you try to add a value that already exists in the Set, the Set simply ignores the duplicate. No error is thrown, and the Set remains unchanged. This makes Sets useful for maintaining collections of unique items.

javascript

const mySet = new Set();

mySet.add('hello');
mySet.add('world');
mySet.add('hello'); // duplicate - ignored

console.log(mySet.size); // 2
console.log(mySet); // Set(2) { 'hello', 'world' }

// Numbers also follow uniqueness
const nums = new Set([10, 20, 30, 10, 20]);
console.log(nums.size); // 3

Use the .has() method to check whether a specific value exists in the Set. It returns true if the value is found and false otherwise.

javascript

const languages = new Set(['JavaScript', 'Python', 'Java']);

console.log(languages.has('JavaScript')); // true
console.log(languages.has('Python'));     // true
console.log(languages.has('C++'));        // false
console.log(languages.has('javascript')); // false (case-sensitive)

Use the .delete() method to remove a specific value from a Set. It returns true if the value was successfully removed and false if the value was not found in the Set.

javascript

const fruits = new Set(['apple', 'banana', 'cherry']);

// Remove an existing element
const removed = fruits.delete('banana');
console.log(removed); // true
console.log(fruits);  // Set(2) { 'apple', 'cherry' }

// Try to remove a non-existent element
const notFound = fruits.delete('grape');
console.log(notFound); // false
console.log(fruits);   // Set(2) { 'apple', 'cherry' }

Use the .size property to get the number of elements in a Set. Note that .size is a property, not a method, so you do not use parentheses.

javascript

const animals = new Set(['cat', 'dog', 'bird', 'fish']);

console.log(animals.size); // 4

// size updates automatically
animals.add('rabbit');
console.log(animals.size); // 5

animals.delete('cat');
console.log(animals.size); // 4

// An empty Set has size 0
const emptySet = new Set();
console.log(emptySet.size); // 0

Use the .clear() method to remove all elements from a Set at once. After calling .clear(), the Set becomes empty and its .size becomes 0.

javascript

const numbers = new Set([1, 2, 3, 4, 5]);

console.log(numbers.size); // 5

// Remove all elements
numbers.clear();

console.log(numbers.size); // 0
console.log(numbers);      // Set(0) {}

A Set can store any type of value - including primitives like numbers, strings, booleans, null, and undefined, as well as objects, arrays, and functions. Each value must be unique within the Set.

javascript

const mixedSet = new Set();

// Primitives
mixedSet.add(42);
mixedSet.add('hello');
mixedSet.add(true);
mixedSet.add(null);
mixedSet.add(undefined);

// Objects and arrays
mixedSet.add({ name: 'Alice' });
mixedSet.add([1, 2, 3]);

console.log(mixedSet.size); // 7

// NaN is treated as equal to NaN in Sets
mixedSet.add(NaN);
mixedSet.add(NaN); // duplicate - ignored
console.log(mixedSet.size); // 8

Sets compare objects by reference, not by value. This means two objects with the same properties are treated as different entries unless they refer to the exact same object in memory.

javascript

const mySet = new Set();

const obj1 = { name: 'Alice' };
const obj2 = { name: 'Alice' };

mySet.add(obj1);
mySet.add(obj2);

// Both are added because they are different references
console.log(mySet.size); // 2

// Same reference is recognized as duplicate
mySet.add(obj1); // duplicate - ignored
console.log(mySet.size); // 2

// Checking membership uses reference comparison
console.log(mySet.has(obj1)); // true
console.log(mySet.has({ name: 'Alice' })); // false (new object)