What is set.size in TypeScript?
Overview
A set is a data structure that stores a collection of unordered and unique entries that are without duplicates. It is different from arrays because, unlike arrays, sets store unique values.
The size property of a set returns the set's size. The size is the number of entries it has.
Syntax
set.size
Return value
The value returned is an integer value that represents the number of entries a set contains.
Example
// create some setslet 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"])let nothing = new Set<null>()// log their sizes to the consoleconsole.log(names.size) // 4console.log(evenNumbers.size) // 6console.log(booleanValues.size) // 2console.log(countries.size) // 5console.log(nothing.size) // 0
Explanation
- Lines 2–6: We create some sets in TypeScript.
- Lines 9–13: We log out the sizes of the sets we have created, to the console.