javascriptecmascript-6

How to get the first element of Set in ES6 ( EcmaScript 2015)


In ES6, how do we quickly get the element?

in MDN Syntax for Set, I didn't find an answer for it.


Solution

  • They don't seem to expose the List to be accessible from the instanced Object. This is from the EcmaScript Draft:

    23.2.4 Properties of Set Instances

    Set instances are ordinary objects that inherit properties from the Set prototype. Set instances also have a [[SetData]] internal slot.

    [[SetData]] is the list of values the Set is holding.

    A possible solution (and a somewhat expensive one) is to grab an iterator and then call next() for the first value:

    var x = new Set();
    x.add(1);
    x.add({ a: 2 });
    //get iterator:
    var it = x.values();
    //get first entry:
    var first = it.next();
    //get value out of the iterator entry:
    var value = first.value;
    console.log(value); //1
    

    Worth mentioning too:

    Set.prototype.values === Set.prototype.keys