JavaScript Set Methods

Essential methods for working with Sets

๐Ÿ› ๏ธ Set Methods Overview

Sets provide powerful methods for adding, removing, and checking values. These methods make Sets perfect for managing unique collections of data.


const mySet = new Set();
mySet.add('apple').add('banana').add('cherry');
console.log(mySet.has('apple')); // true
console.log(mySet.size); // 3
                                    

Output:

true
3

Core Set Methods

โž•

add()

Adds a new value to the Set

set.add('value');
set.add(42);
โŒ

delete()

Removes a value from the Set

set.delete('value');
// Returns true if deleted
๐Ÿ”

has()

Checks if value exists in Set

set.has('value');
// Returns true/false
๐Ÿงน

clear()

Removes all values from Set

set.clear();
// Set becomes empty

๐Ÿ”น add() Method

The add() method adds a new element to the Set and returns the Set object:

const colors = new Set();

// Adding single values
colors.add('red');
colors.add('blue');
colors.add('green');

// Method chaining
colors.add('yellow').add('purple').add('orange');

// Adding duplicate (ignored)
colors.add('red'); // Won't be added

console.log(colors);
console.log(colors.size); // 6

Output:

Set {'red', 'blue', 'green', 'yellow', 'purple', 'orange'}
6

๐Ÿ”น delete() Method

The delete() method removes an element and returns true if successful:

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

// Delete existing value
console.log(numbers.delete(3)); // true
console.log(numbers.has(3)); // false

// Delete non-existing value
console.log(numbers.delete(10)); // false

console.log(numbers); // Set {1, 2, 4, 5}
console.log(numbers.size); // 4

Output:

true
false
false
Set {1, 2, 4, 5}
4

๐Ÿ”น has() Method

The has() method checks if a value exists in the Set:

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

// Check existing values
console.log(fruits.has('apple')); // true
console.log(fruits.has('banana')); // true

// Check non-existing values
console.log(fruits.has('grape')); // false
console.log(fruits.has('APPLE')); // false (case sensitive)

// Works with any data type
const mixedSet = new Set([1, 'hello', true, null]);
console.log(mixedSet.has(1)); // true
console.log(mixedSet.has(true)); // true
console.log(mixedSet.has(null)); // true

Output:

true
true
false
false
true
true
true

๐Ÿ”น Iteration Methods

Sets provide several ways to iterate through values:

๐Ÿ”ธ forEach() Method

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

// forEach with callback function
animals.forEach(animal => {
    console.log(animal);
});

// forEach with index (same as value in Sets)
animals.forEach((value, key, set) => {
    console.log(`${key}: ${value}`);
});

Output:

cat
dog
bird
cat: cat
dog: dog
bird: bird

๐Ÿ”ธ for...of Loop

const scores = new Set([85, 92, 78, 96]);

for (const score of scores) {
    console.log(`Score: ${score}`);
}

Output:

Score: 85
Score: 92
Score: 78
Score: 96

๐Ÿ”น Converting Sets

Convert Sets to arrays and vice versa:

// Set to Array
const mySet = new Set([1, 2, 3, 4]);
const myArray = [...mySet]; // Using spread operator
const myArray2 = Array.from(mySet); // Using Array.from()

console.log(myArray); // [1, 2, 3, 4]

// Array to Set (removes duplicates)
const duplicateArray = [1, 1, 2, 2, 3, 3];
const uniqueSet = new Set(duplicateArray);
console.log(uniqueSet); // Set {1, 2, 3}

// Back to unique array
const uniqueArray = [...uniqueSet];
console.log(uniqueArray); // [1, 2, 3]

Output:

[1, 2, 3, 4]
Set {1, 2, 3}
[1, 2, 3]

๐Ÿง  Test Your Knowledge

What does the delete() method return when successfully removing an element?