Sets

All about Sets in JavaScript


Set is a built-in object collection of unique values, where duplicates are not allowed.

A Set can store any type of value, including objects, and provides methods to add, remove, and check if a value exists in the set.

const mySet = new Set()

LinkIconadd()

mySet.add(1)
mySet.add("two")
mySet.add(true)

LinkIcondelete()

mySet.delete(2)
// => {1, "two"}

LinkIconsize

mySet.size
// => 2

LinkIconhas()

mySet.has(1) // => true
mySet.has("three") // => false

LinkIconforEach()

mySet.forEach((value) => {
  console.log(value)
})
// 1
// "two"

LinkIconfor of

for (let value of mySet) {
  console.log(value)
}
// 1
// "two"

LinkIconclear()

mySet.clear() // => {}

LinkIconArray to Set

Convert an Array to Set.

let arrayToSet = new Set(arr)