Skip to main content

Javascript Object Sets

JavaScript Sets are objects that allow you to store unique values of any type, such as numbers, strings, objects, or other data types.

Unlike arrays, Sets do not allow duplicate values, which makes them useful for managing collections of unique items.

Sets are part of the ECMAScript 6 (ES6) standard, also known as ES2015, and are supported by modern web browsers and JavaScript environments.

Key features of JavaScript Sets

Unique values

Sets only allow unique values. If you try to add a duplicate value to a Set, it will be ignored.

No index-based access

Unlike arrays, Sets do not have indices or keys to access values. Instead, you can use methods like has(), add(), delete(), and clear() to interact with the values in a Set.

Iteration

Sets are iterable, which means you can loop through their values using a for...of loop or by using the forEach() method.

No implicit type coercion

Sets do not perform implicit type coercion, which means that values of different types are treated as distinct values. For example, a string "1" and a number 1 are considered different values in a Set.

Equality and comparison

Sets use the SameValueZero algorithm for equality and comparison, which means that NaN is considered equal to NaN, and +0 is considered equal to -0.

Size tracking

Sets automatically keep track of the number of elements they contain using the size property, which makes it easy to determine the size of a Set.

Here's an example of creating, adding, and iterating over a Set in JavaScript:

// Creating a Set
const mySet = new Set();

// Adding values to the Set
mySet.add(1);
mySet.add("Hello");
mySet.add({name: "John"});

// Checking if a value is in the Set
console.log(mySet.has(1)); // true

// Deleting a value from the Set
mySet.delete("Hello");

// Looping through the Set
for (const value of mySet) {
console.log(value);
}

// Output:
// 1
// { name: "John" }

Set Methods

MethodDescription
new Set()Creates a new Set
add()Adds a new element to the Set
delete()Removes an element from a Set
has()Returns true if a value exists
clear()Removes all elements from a Set
forEach()Invokes a callback for each element
values()Returns an Iterator with all the values in a Set
keys()Same as values()
entries()Returns an Iterator with the [value,value] pairs from a Set

How to Create a Set

Creating a Set in JavaScript is simple and can be done using the Set constructor or by using an iterable (e.g., an array) as an argument to the Set constructor. Here are some examples:

  • Creating an empty Set using the Set constructor:
const mySet = new Set();
  • Creating a Set with initial values using an array:
const myArray = [1, 2, 3, 4, 5];
const mySet = new Set(myArray);
  • Adding values to a Set:
const mySet = new Set();
mySet.add(1);
mySet.add("Hello");
mySet.add({name: "John"});
  • Creating a Set with initial values using an array and then chaining add() method:
const myArray = [1, 2, 3, 4, 5];
const mySet = new Set().add(1).add(2).add(3).add(4).add(5);
tip

Note that Sets only allow unique values, so attempting to add a duplicate value to a Set will be ignored.

  • Creating a Set with values in a single line using an array spread syntax:
const myArray = [1, 2, 3, 4, 5];
const mySet = new Set([...myArray]);

This creates a new Set and spreads the values of the array into the Set using the spread syntax ([...myArray]).

Once you have created a Set, you can use the various methods provided by the Set object, such as add(), has(), delete(), clear(), and forEach(), to interact with the values in the Set as needed.

The add() Method

The add() method in JavaScript Sets is used to add a new value to the Set. The add() method returns the Set object, which allows for method chaining.

The syntax for the add() method is as follows:

mySet.add(value);

where mySet is the Set object to which you want to add the value, and value is the value you want to add to the Set.

Here's an example of using the add() method to add values to a Set:

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

// Adding values to the Set
mySet.add(1);
mySet.add("Hello");
mySet.add({name: "John"});

// Adding values using method chaining
mySet.add(2).add("World");

// Checking if a value is in the Set
console.log(mySet.has(1)); // true

// Output:
// Set { 1, 'Hello', { name: 'John' }, 2, 'World' }

In the example:

  • We create an empty Set called mySet, and then we use the add() method to add various values to the Set, including numbers, strings, and objects.
  • We also demonstrate how method chaining can be used to add multiple values in a single line.

The forEach() Method

The forEach() method in JavaScript Sets is used to iterate over the values in a Set and execute a provided function for each value. The forEach() method does not modify the Set and does not return any value.

The syntax for the forEach() method is as follows:

mySet.forEach(callbackFunction);

Where mySet is the Set object that you want to iterate over, and callbackFunction is the function to be executed for each value in the Set.

The callbackFunction is called with three arguments for each iteration:

  • value: The current value being iterated in the Set.
  • key: The same as value as Sets do not have keys. This is included for consistency with the forEach() method in Map objects.
  • set: The Set object that the forEach() method was called on.

Here's an example of using the forEach() method to iterate over the values in a Set:

// Creating a Set
const mySet = new Set();
mySet.add(1);
mySet.add("Hello");
mySet.add({name: "John"});

// Using forEach() to iterate over the values
mySet.forEach((value, key, set) => {
console.log(value);
});

// Output:
// 1
// Hello
// { name: 'John' }

In the example:

  • We create a Set called mySet and add several values to it.
  • Then, we use the forEach() method to iterate over the values in the Set and log them to the console.

The values() Method

The values() method in JavaScript Sets is used to retrieve an iterator object that contains the values of the Set in insertion order. The iterator object can be used to iterate over the values of the Set using a loop or other iterable methods.

The syntax for the values() method is as follows:

mySet.values();

Where mySet is the Set object for which you want to retrieve the values.

Here's an example of using the values() method to iterate over the values in a Set using a for...of loop:

// Creating a Set
const mySet = new Set();
mySet.add(1);
mySet.add("Hello");
mySet.add({name: "John"});

// Retrieving the iterator object using values()
const setValues = mySet.values();

// Iterating over the values using a for...of loop
for (const value of setValues) {
console.log(value);
}

// Output:
// 1
// Hello
// { name: 'John' }

In the example:

  • We create a Set called mySet and add several values to it.
  • Then, we use the values() method to retrieve the iterator object setValues that contains the values of the Set.
  • Finally, we iterate over the values using a for...of loop and log them to the console.

The entries() Method

Sets do have an entries() method that can be used to retrieve an iterator object containing arrays of [value, value] pairs, where each value in the Set is both the key and the value. The iterator object can be used to iterate over the entries of the Set, which are in insertion order.

The syntax for the entries() method is as follows:

mySet.entries();

Where mySet is the Set object for which you want to retrieve the entries.

Here's an example of using the entries() method to iterate over the entries (value-value pairs) in a Set using a for...of loop:

// Creating a Set
const mySet = new Set();
mySet.add(1);
mySet.add("Hello");
mySet.add({name: "John"});

// Retrieving the iterator object using entries()
const setEntries = mySet.entries();

// Iterating over the entries using a for...of loop
for (const entry of setEntries) {
console.log(entry);
}

// Output:
// [1, 1]
// ['Hello', 'Hello']
// [{ name: 'John' }, { name: 'John' }]

In the example:

  • We create a Set called mySet and add several values to it.
  • Then, we use the entries() method to retrieve the iterator object esetEntris that contains the entries (value-value pairs) of the Set.
  • Finally, we iterate over the entries using a for...of loop and log them to the console. Note that each entry is an array containing the value repeated twice, as Sets do not have separate keys and values.