What is the set.clear() method in TypeScript?

Overview

A set is a collection of values that are unique and without duplicates. Arrays are similar to sets. The only difference is that sets can only have unique elements. In TypeScript, the clear() method is used to remove everything from the set.

Syntax

set.clear()
syntax for clear() method of a Set in Typescript

Parameters

set: This is the set we want to clear all the values of.

Return value

This method returns an empty set.

Example

// create some sets
let names = new Set<string>(["Theodore", "David", "John", "Janme"])
let evenNumbers = new Set<number>([2, 4, 6, 8, 10, 12])
let booleanValues = new Set<boolean>([true, false])
let countries = new Set<string>(["Nigeria", "Brazil", "Ghana", "Egypt", "Germany"])
// logout all sets
console.log("Before clearing sets")
console.log(names)
console.log(evenNumbers)
console.log(booleanValues)
console.log(countries)
// clear the sets
names.clear()
evenNumbers.clear()
booleanValues.clear()
countries.clear()
// logout empty sets
console.log("After clearing sets")
console.log(names)
console.log(evenNumbers)
console.log(booleanValues)
console.log(countries)

Explanation

  • Lines 2–5: We create some sets.
  • Lines 8–12: We log out the sets before clearing the entries.
  • Lines 15–18: We use the clear() method to clear all the entries of the sets.
  • Lines 22–25: We log out the sets to the console once again.