Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript

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

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
Clear all entries of a Set in TypeScript

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.

RELATED TAGS

typescript

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring