You can create a new Set in JavaScript using the Set constructor. Here's how you can do it:
const mySet = new Set();
In the above code, mySet is a new Set that is initially empty. You can also create a Set with an iterable, such as an array or another Set, by passing it as an argument to the
Set constructor. For example:
const mySet = new Set([1, 2, 3, 4]);
This creates a new Set called mySet with the elements 1, 2, 3, and 4. The Set will automatically eliminate any duplicate values, so you'll end up with a Set containing unique elements.
You can also add elements to the Set later using the add method:
mySet.add(5);
mySet.add(6);
Now, mySet contains the elements 1, 2, 3, 4, 5, and 6.
Sets in JavaScript are a useful data structure for maintaining collections of unique values, and they provide various methods for adding, removing, and checking the existence of elements.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
You can create a new Set in JavaScript using the Set constructor. Here's how you can do it:
In the above code, mySet is a new Set that is initially empty. You can also create a Set with an iterable, such as an array or another Set, by passing it as an argument to the Set constructor. For example:
This creates a new Set called mySet with the elements 1, 2, 3, and 4. The Set will automatically eliminate any duplicate values, so you'll end up with a Set containing unique elements.
You can also add elements to the Set later using the add method:
Now, mySet contains the elements 1, 2, 3, 4, 5, and 6.
Sets in JavaScript are a useful data structure for maintaining collections of unique values, and they provide various methods for adding, removing, and checking the existence of elements.