A set is a data structure that stores data that is unique and without duplicates. We use the add()
method to add a value to a set.
theSet.add(value)// Or chain the add() methodtheSet.add(value1).add(value2).add(valueN)
Note: This method can be chained as shown in the syntax above.
theSet
: This is the set to which we want to add values.
value1
, value2
, and valueN
: These are the values we want to add to the set.
The value returned is a new set with the value added to it.
// create some set instanceslet names = new Set<string>()let evenNumbers = new Set<number>()let countries = new Set<string>()let isMarried = new Set<boolean>()// add values to the setsnames.add("Theodore")names.add("Celeste")names.add("Dave")evenNumbers.add(2).add(4).add(8).add(10)countries.add("Nigeria").add("Puerto Rico").add("Chile").add("India")isMarried.add(true)isMarried.add(false)// log out all the setsconsole.log(names)console.log(evenNumbers)console.log(countries)console.log(isMarried)
add()
method to add values to the sets.