Learn about JavaScript Sets, a built-in data structure for managing unique values efficiently. Explore methods, examples, and best practices for working with Sets in your JavaScript projects.
JavaScript Sets are a built-in data structure introduced in ECMAScript 6 (ES6) that allow you to store a collection of unique values.
Sets are similar to arrays but with a few key differences:
In JavaScript, there are a few methods to create a Set:
Here’s how you can create and work with Sets in JavaScript:
You can create a Set using the Set constructor:
const mySet = new Set();
The most common way to create a Set is by using the new Set() constructor. It initializes an empty Set, and you can add values to it
using the add method:
const mySet = new Set(); mySet.add(1); mySet.add('Hello'); mySet.add({ key: 'value' });
You can create a Set from an iterable, such as an array, using the Set constructor.
This is useful when you want to initialize a Set with existing values:
const initialValues = [1, 2, 3, 4, 5]; const mySet = new Set(initialValues);
<!DOCTYPE html> <html> <head> <title>JavaScript Set Example</title> </head> <body> <h1>JavaScript Set Example</h1> <script> // Create a Set const initialValues = [1, 2, 3, 4, 5]; const mySet = new Set(initialValues); document.write('Set size:', mySet.size +"<br>"); // Iterate over the Set mySet.forEach(value => { document.write ('Set value:', value +"<br>"); }); // Check if values exist in the Set document.write ('Has "one":', 1+"<br>"); document.write ('Has "tow":', 2+"<br>"); // Delete a value from the Set mySet.delete(1); // Display the updated Set document.write ('Updated Set:', mySet); </script> </body> </html>
You can create a Set from an array using the spread operator (…):
const initialValues = [1, 2, 3, 4, 5]; const mySet = new Set([...initialValues]);
complete code example:
<!DOCTYPE html> <html> <head> <title>JavaScript Set Example</title> </head> <body> <h1>JavaScript Set Example</h1> <script> // Create a Set const initialValues = [50, 100, 200, 300,'gogo','World']; const mySet = new Set([...initialValues]); document.write('Set size:', mySet.size +"<br>"); // Iterate over the Set mySet.forEach(value => { document.write ('Set value:', value +"<br>"); }); </script> </body> </html>
If you want to create a Set with values in a single line, you can chain the add method:
const mySet = new Set().add(1).add('Hello').add({ key: 'value' });
Remember that Sets automatically remove duplicates, so even if you add duplicate values, the Set will only contain unique values. Sets are particularly useful when you need to work with collections of unique values and perform set operations like union, intersection, and difference.
<!DOCTYPE html> <html> <head> <title>JavaScript Set Example</title> </head> <body> <h1>JavaScript Set Example</h1> <script> // Create a Set using one line const mySet = new Set().add(1).add('Hello').add({ key: 'value' }); document.write('Set size:', mySet.size +"<br>"); // Iterate over the Set mySet.forEach(value => { document.write ('Set value:', value +"<br>"); }); </script> </body> </html>
Here’s a complete HTML and JavaScript example that demonstrates how to create a Set using the new Set() constructor and add values to it:
<!DOCTYPE html> <html> <head> <title>JavaScript Set Example</title> </head> <body> <h1>JavaScript Set Example</h1> <p>Open the browser console to see the output.</p> <script> // Create a Set using the new Set() constructor const mySet = new Set(); // Add values to the Set mySet.add(1); mySet.add('Hello'); mySet.add({ key: 'value' }); // Display the Set's size and contents console.log('Set size:', mySet.size); // Iterate over the Set and display its values mySet.forEach(value => { console.log('Set value:', value); }); </script> </body> </html>
In this HTML document, we create a Set named mySet using the new Set() constructor, add values to it, display its size and contents, and iterate over its elements. To see the output, open the browser’s developer console while viewing this HTML page.
Creating a Set from an iterable, such as an array, is quite straightforward in JavaScript.
Here’s a complete HTML and JavaScript example that demonstrates how to create a Set from an iterable:
<!DOCTYPE html> <html> <head> <title>JavaScript Set from Iterable Example</title> </head> <body> <h1>JavaScript Set from Iterable Example</h1> <p>Open the browser console to see the output.</p> <script> // Create an iterable (an array in this case) const initialValues = [1, 2, 3, 4, 5]; // Create a Set from the iterable const mySet = new Set(initialValues); // Display the Set's size and contents document.write('Set size:', mySet.size +"<br>"); // Iterate over the Set and display its values mySet.forEach(value => { document.write('Set value:', value +"<br>"); }); </script> </body> </html>
To see the output, open the browser’s developer console while viewing this HTML page.
Creating a Set from an array using the spread operator is a concise and efficient way to initialize a Set.
Here’s a complete HTML and JavaScript example that demonstrates how to do this:
<!DOCTYPE html> <html> <head> <title>JavaScript Set from Array using Spread Operator</title> </head> <body> <h1>JavaScript Set from Array using Spread Operator</h1> <p>Open the browser console to see the output.</p> <script> // Create an array const initialValues = [1, 2, 3, 4, 5]; // Create a Set from the array using the spread operator const mySet = new Set([...initialValues]); // Display the Set's size and contents document.write('Set size:', mySet.size +"<br>"); // Iterate over the Set and display its values mySet.forEach(value => { document.write('Set value:', value +"<br>"); }); </script> </body> </html>
In this HTML document:
To see the output, open the browser’s developer console while viewing this HTML page.
Adding and Removing Values
You can add values to a Set using the add method:
mySet.add(1); mySet.add('Hello'); mySet.add({ key: 'value' });
To remove a value from a Set, you can use the delete method:
mySet.delete(1);
Checking if a Value Exists
You can check if a value exists in a Set using the has method:
console.log(mySet.has('Hello')); // true console.log(mySet.has(1)); // false
You can iterate over the values in a Set using the forEach method or a for…of loop:
mySet.forEach(value => { console.log(value); }); for (const value of mySet) { console.log(value); }
Getting the Size of a Set
You can get the number of elements in a Set using the size property:
console.log(mySet.size);
Converting a Set to an Array
If you need to convert a Set to an array, you can use the Array.from method or the spread operator:
const setToArray = Array.from(mySet); const setToArray2 = [...mySet];
Sets in JavaScript come with a variety of methods for adding, removing, checking, and manipulating data. Below is a list of the essential Set methods:
add(value):
Adds a new element with the given value to the Set. If the element already exists, it does nothing.
mySet.add(1);
delete(value):
Removes the element with the specified value from the Set. Returns true if the element was in the Set; otherwise, returns false.
mySet.delete(1);
has(value):
Checks whether the Set contains an element with the specified value. Returns true if it exists; otherwise, returns false.
const hasValue = mySet.has(1);
clear():
Removes all elements from the Set, making it empty.
mySet.clear();
size:
Returns the number of elements in the Set. This property is read-only.
const setSize = mySet.size;
forEach(callbackFn, thisArg): Calls a provided function once for each value in the Set, in insertion order.
mySet.forEach(value => {
console.log(value);
});
values():
Returns an iterator of all values in the Set, in insertion order. This method is used implicitly when using a for…of loop on a Set.
for (const value of mySet.values()) {
console.log(value);
}
keys():
Returns an iterator of all values in the Set, in insertion order. This method is also used implicitly when using a for…of loop.
for (const key of mySet.keys()) {
console.log(key);
}
entries():
Returns an iterator of entries (key-value pairs) where both the key and value are the same. It’s primarily used for compatibility with Map objects.
for (const entry of mySet.entries()) {
console.log(entry);
}
These are the fundamental methods of JavaScript Sets. Sets are useful when you need to work with collections of unique values, and these methods allow you to perform various operations on them efficiently.
add(value): complete code in html
Here’s a complete HTML and JavaScript example that demonstrates how to use the add(value) method to add values to a Set:
<!DOCTYPE html> <html> <head> <title>JavaScript Set add() Method Example</title> </head> <body> <h1>JavaScript Set add() Method Example</h1> <script> // Create a Set const mySet = new Set(); // Add values to the Set using the add() method mySet.add(1); mySet.add('Hello'); mySet.add({ key: 'value' }); // Display the Set's size and contents document.write('Set size:', mySet.size +"<br>"); // Iterate over the Set and display its values mySet.forEach(value => { document.write('Set value:', value +"<br>"); }); </script> </body> </html>
delete(value): complete code in html
Here’s a complete HTML and JavaScript example that demonstrates how to use the delete(value) method to remove a specific value from a Set:
<!DOCTYPE html> <html> <head> <title>JavaScript Set delete() Method Example</title> </head> <body> <h1>JavaScript Set delete() Method Example</h1> <p>Open the browser console to see the output.</p> <script> // Create a Set const mySet = new Set(); // Add values to the Set using the add() method mySet.add(1); mySet.add('Hello'); mySet.add({ key: 'value' }); // Display the Set's size and contents console.log('Set size:', mySet.size); // Attempt to delete a value from the Set const deleted = mySet.delete(1); // Display the result of the deletion console.log('Deleted:', deleted); // Display the updated Set's size and contents console.log('Updated Set size:', mySet.size); // Iterate over the Set and display its values mySet.forEach(value => { console.log('Set value:', value); }); </script> </body> </html>
In this HTML document:
To see the output, open the browser’s developer console while viewing this HTML page.
Here’s a complete HTML and JavaScript example that demonstrates how to use the has(value) method to check if a specific value exists in a Set:
<!DOCTYPE html> <html> <head> <title>JavaScript Set has() Method Example</title> </head> <body> <h1>JavaScript Set has() Method Example</h1> <script> // Create a Set const mySet = new Set(); // Add values to the Set using the add() method mySet.add(1); mySet.add('Hello'); mySet.add({ key: 'value' }); // Display the Set's size and contents document.write('Set size:', mySet.size +"<br>"); // Check if a value exists in the Set using the has() method const hasHello = mySet.has('Hello'); const hasWorld = mySet.has('World'); // Display the results document.write('Has "Hello":', hasHello +"<br>"); // Should be true document.write('Has "World":', hasWorld +"<br>"); // Should be false // Iterate over the Set and display its values mySet.forEach(value => { document.write('Set value:', value +"<br>"); }); </script> </body> </html>
In this HTML document:
To see the output, open the browser’s developer console while viewing this HTML page.
Here’s a complete HTML and JavaScript example that demonstrates how to use the clear() method to remove all elements from a Set:
<!DOCTYPE html> <html> <head> <title>JavaScript Set clear() Method Example</title> </head> <body> <h1>JavaScript Set clear() Method Example</h1> <script> // Create a Set const mySet = new Set(); // Add values to the Set using the add() method mySet.add(1); mySet.add('gogo'); mySet.add({ key: 'value' }); // Display the Set's size and contents document.write('Set size before clear:', mySet.size +"<br>"); // Clear all elements from the Set using the clear() method mySet.clear(); // Display the Set's size after clear (should be 0) and contents (empty) document.write('Set size after clear:', mySet.size +"<br>"); // Iterate over the Set (should not display anything as it's empty) mySet.forEach(value => { document.write('Set value:', value +"<br>"); }); </script> </body> </html>
In this HTML document:
Here’s a complete HTML and JavaScript example that demonstrates how to use the size property to get the number of elements in a Set:
<!DOCTYPE html> <html> <head> <title>JavaScript Set size Property Example</title> </head> <body> <h1>JavaScript Set size Property Example</h1> <p>Open the browser console to see the output.</p> <script> // Create a Set const mySet = new Set(); // Add values to the Set using the add() method mySet.add(1); mySet.add('Hello'); mySet.add({ key: 'value' }); // Get the size of the Set using the size property const setSize = mySet.size; // Display the Set's size and contents console.log('Set size:', setSize); // Iterate over the Set and display its values mySet.forEach(value => { console.log('Set value:', value); }); </script> </body> </html>
In this HTML document:
Here’s a complete HTML and JavaScript example that demonstrates how to use the forEach(callbackFn, thisArg) method to iterate over the elements of a Set:
<!DOCTYPE html> <html> <head> <title>JavaScript Set forEach() Method Example</title> </head> <body> <h1>JavaScript Set forEach() Method Example</h1> <p>Open the browser console to see the output.</p> <script> // Create a Set const mySet = new Set(); // Add values to the Set using the add() method mySet.add(1); mySet.add('Hello'); mySet.add({ key: 'value' }); // Define a callback function to be used with forEach() function displayValue(value) { console.log('Set value:', value); } // Use the forEach() method to iterate over the Set mySet.forEach(displayValue); // You can also specify a "thisArg" if needed const customThis = { message: 'Custom This Context' }; function displayValueWithThis(value) { console.log('Set value:', value, 'with this context:', this.message); } mySet.forEach(displayValueWithThis, customThis); </script> </body> </html>
In this HTML document:
To see the output, open the browser’s developer console while viewing this HTML page.
The values() method for Sets is the default iterator for Set objects. You can iterate over the values of a Set using a for…of loop without explicitly calling values().
Here’s a complete HTML and JavaScript example demonstrating this:
<!DOCTYPE html> <html> <head> <title>JavaScript Set values() Method Example</title> </head> <body> <h1>JavaScript Set values() Method Example</h1> <p>Open the browser console to see the output.</p> <script> // Create a Set const mySet = new Set(); // Add values to the Set using the add() method mySet.add(1); mySet.add('Hello'); mySet.add({ key: 'value' }); // Iterate over the Set using a for...of loop (no need to call values()) for (const value of mySet) { console.log('Set value:', value); } </script> </body> </html>
In this HTML document:
Open the browser’s developer console while viewing this HTML page to see the output, which will display each value in the Set.
In JavaScript, Sets do not have a keys() method like Maps do. Sets store only values, and there are no keys associated with individual values in a Set.
To iterate over the values in a Set, you can use the default iterator or a for…of loop, as demonstrated in the previous example.
If you need to use keys() as you would with a Map, you can create a Map where both keys and values are the same and then use the keys() method on that Map.
Here’s an example:
<!DOCTYPE html> <html> <head> <title>JavaScript Set keys() Method Example (via Map)</title> </head> <body> <h1>JavaScript Set keys() Method Example (via Map)</h1> <p>Open the browser console to see the output.</p> <script> // Create a Set const mySet = new Set(); // Add values to the Set using the add() method mySet.add(1); mySet.add('Hello'); mySet.add({ key: 'value' }); // Create a Map where both keys and values are the same const myMap = new Map([...mySet].map(value => [value, value])); // Use the keys() method of the Map to iterate over keys/values for (const key of myMap.keys()) { console.log('Map key/value:', key); } </script> </body> </html>
In this HTML document:
Open the browser’s developer console while viewing this HTML page to see the output.
In JavaScript, Sets do not have a entries() method like Maps do.
Sets store only values, and there are no keys associated with individual values in a Set. The entries() method in a Map returns an iterator of key-value pairs, which is not applicable to Sets.
If you need to use entries() as you would with a Map, you can create a Map where both keys and values are the same and then use the entries() method on that Map.
Here’s an example:
<!DOCTYPE html> <html> <head> <title>JavaScript Set entries() Method Example (via Map)</title> </head> <body> <h1>JavaScript Set entries() Method Example (via Map)</h1> <p>Open the browser console to see the output.</p> <script> // Create a Set const mySet = new Set(); // Add values to the Set using the add() method mySet.add(1); mySet.add('Hello'); mySet.add({ key: 'value' }); // Create a Map where both keys and values are the same const myMap = new Map([...mySet].map(value => [value, value])); // Use the entries() method of the Map to iterate over key-value pairs for (const [key, value] of myMap.entries()) { console.log('Map key:', key, 'value:', value); } </script> </body> </html>
In this HTML document:
Open the browser’s developer console while viewing this HTML page to see the output.
Here’s a quiz with answers about Sets in JavaScript:
Answer: A Set is a built-in data structure in JavaScript that allows you to store a collection of unique values.
Answer: You can create an empty Set by using the new Set() constructor.
Answer: Sets only store unique values, so if you try to add a duplicate value, it won’t result in duplicate entries. The value will be ignored.
Answer: You can use the has(value) method to check if a specific value exists in a Set. It returns true if the value is found and false if it’s not.
Answer: You can use the delete(value) method to remove a specific value from a Set. It returns true if the value was in the Set and false if it wasn’t.
Answer: You can use the size property to get the number of elements in a Set. For example, mySet.size returns the size of the Set mySet.
Answer: You can iterate over the values of a Set using the forEach(callbackFn) method or by using a for…of loop directly on the Set.
Answer: No, Sets do not have built-in indexing like arrays. You cannot access elements by their index in a Set.
Answer: You can use the clear() method to remove all elements from a Set, making it empty.
**Answer:** No, Sets automatically remove duplicates, so they can only contain unique values.
MDN Web Docs – Set
W3Schools – JavaScript Set:
W3Schools – JavaScript Set
JavaScript.info –
JavaScript.info – Set
Eloquent JavaScript – Chapter 7: Data Structures: Objects and Arrays: This online book by Marijn Haverbeke covers Sets and other data structures in JavaScript.