Set.prototype.add
Adds a value to a Set if it is not there yet.
Available since: ES2015
Syntax
set.add(value)Parameters
| Parameter | Type | Description |
|---|---|---|
| value | any | The value to add. |
Return value
SetThe same Set — calls can be chained.
Examples
Adding a value twice changes nothing:
const visited = new Set();
visited.add('home').add('about').add('home');
console.log(visited.size);
console.log([...visited].join(', '));Output:
2
home, aboutNotes
There is no error on a repeated add — the value just is not added a second time.
See also
- Set.prototype.has — Checks whether a value is in a Set.
- Set.prototype.delete — Removes a value from a Set.
- Array.prototype.push — Appends elements to the end of an array.
In the tutorial
- Map and Set — The Map and Set collections in JavaScript: a dictionary with keys of any type and a set of unique values.