DEV Community

Tejasvi Shinde
Tejasvi Shinde

Posted on

JavaScript Set

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();
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Note: Set has a size property, not a length property.

Top comments (0)