What the heck the "new Set()" is?

It’s kinda returns an object, but objects have a pair prop: 'val', but ‘Set’ has only one prop/val(?)…

When I do console.log(new Set([1,2,3,4,4,5,5,5,6])) in my console I have this result Set(5) {1, 2, 3, 4, 5,6}.

As I remember it’s one of the ES6 feature but I’m not sure.

Set is the collection of the unique values. You may initialize a new Set with an array. Sometimes you may use this trick to get rid of duplicates in the array.

Do I understand correctly that this is the another type of JS?

You may call it a type if you’d rather, in terms of structural typing, but basically it’s just the built-in object with its own set of props and methods. As I understand it.

1 Like

To start from afar, when we say new, its to create a new object via constructor/class. There are built in JS, but you can also create your own. Array is built in class, so is Date, RegExp and many more. You say new Array and you get new array, ofc often requires some parameters to be provided. Whenever you need to work with a foreign class, e.g. you encounter new Set, its best to look in the docs to get a better idea what this class is about. Once the object is created, it inherits some predefined methods to be utilized. Just like arrays have all those methods. Basically they inherit it from the Array class. Ofc, sets are not that core and widely used/developed. They have kinda niche use. There are lot more commonly used objects, id say even RegExp goes far ahead.

1 Like

It’s a type of object, like plain objects, or arrays, or maps. It’s used when you want a collection of unique items and you want the computer to ensure they’re unique without having to write logic to check.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.