How to Create a Set in JavaScript: Syntax and Examples
In JavaScript, you create a set using the
Set constructor like new Set(). A set stores unique values, so duplicates are automatically removed.Syntax
The basic syntax to create a set is using the Set constructor. You can create an empty set or initialize it with an array of values.
new Set(): creates an empty set.new Set(iterable): creates a set with unique values from the iterable (like an array).
javascript
const emptySet = new Set(); const numberSet = new Set([1, 2, 3, 2]);
Example
This example shows how to create a set, add values, and see that duplicates are removed automatically.
javascript
const fruits = new Set(['apple', 'banana', 'apple', 'orange']); console.log(fruits); console.log(fruits.has('banana')); fruits.add('grape'); console.log([...fruits]);
Output
Set(3) { 'apple', 'banana', 'orange' }
true
[ 'apple', 'banana', 'orange', 'grape' ]
Common Pitfalls
Common mistakes include trying to create a set without new, or expecting sets to keep duplicate values.
Also, sets compare objects by reference, so two different objects with the same content are treated as different.
javascript
/* Wrong: missing 'new' keyword */ // const mySet = Set([1, 2, 3]); // This throws an error /* Right: use 'new' */ const mySet = new Set([1, 2, 3]); /* Objects in sets */ const obj1 = {a: 1}; const obj2 = {a: 1}; const objSet = new Set([obj1, obj2]); console.log(objSet.size); // 2 because obj1 and obj2 are different objects
Output
2
Quick Reference
- Create empty set:
new Set() - Create set with values:
new Set([values]) - Add value:
set.add(value) - Check value:
set.has(value) - Remove value:
set.delete(value) - Clear all:
set.clear()
Key Takeaways
Use
new Set() to create a set in JavaScript.Sets store only unique values; duplicates are automatically removed.
Always use the
new keyword when creating a set.Sets compare objects by reference, not by content.
Use
add, has, and delete methods to manage set items.