Javascript set object does not allow duplicate values to be pushed it contains only unique values.
First, we declare a variable set using const in which we assign a set object with a new keyword.
const animals = new Set();
Now, we add animals to set variable using set object add() method.
animals.add('🐷');
animals.add('🐴');
console.log(animals.size); // 2
animals.add('🐴');
console.log(animals.size); // 2
Javascript set only store unique values either it’s for string or number or object. So, the set will neglect the 🐴 add when he found out the same value again.
Strings are a valid iterable so they can also be passed-in to initialize a set
console.log('Happy Coding'.length); // 13
let sentence = new Set('Happy Coding'); //12
console.log(sentence.size);
Note: Set has a size property, not a length property.
Top comments (0)