JavaScript Reference ยท Collections
Set.prototype.add(), has() and delete()
Reference for the core JavaScript Set methods add(), has(), delete() and clear(): what each returns, how duplicates are handled and common patterns.
Three methods cover most everyday work with a Set. add(value) inserts a value and returns the set itself, which allows chaining. has(value) returns a boolean saying whether the value is a member. delete(value) removes the value and returns true if it was there, false otherwise. clear() empties the set.
Adding a value that is already present does nothing: the set stays the same and the value keeps its original position.
const seen = new Set(); seen.add("a").add("b").add("a"); // Set { "a", "b" } seen.has("a"); // true seen.delete("a"); // true
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
set.add(value) set.has(value) set.delete(value) set.clear()
| Name | Description |
|---|---|
value |
The value to add, test for or remove. Any type is allowed. Compared with "same value zero": like ===, but NaN equals NaN. |
Return value: add() returns the set. has() and delete() return a boolean. clear() returns undefined.
Exceptions: none for ordinary use; calling the methods on something that is not a Set throws a TypeError.
Usage notes
add()cannot tell you if the value was new. Comparesizebefore and after, or callhas()first, when you need to know. A trick:const isNew = !set.has(v) && (set.add(v), true).delete()doubles as an existence check, which makes "toggle" logic a one-liner (see the second example).- Chaining. Because
add()returns the set,new Set().add(1).add(2)works.delete()does not return the set, so it cannot be chained. - Deleting while iterating is safe. Removed members that were not yet reached are skipped. Members added during the loop are visited, so a loop that keeps adding can run forever.
- Position rules. Re-adding an existing value does not move it. Deleting a value and adding it again places it at the end.
- Fast operations.
add(),has()anddelete()take roughly constant time, regardless of the size of the set. NaNand zero.NaNcan be added once and found again withhas(NaN).+0and-0are the same member.- Not the
deleteoperator.delete set.xonly affects object properties.
Browser support
add(), has(), delete() and clear() work in every current browser and in Node.js.