0

Given this set, the iterator functions are strictly equal, but not when called:

let set = new Set([1,2,'3']);

console.log(set.keys === set.values);              // true
console.log(set.keys === set[Symbol.iterator]);    // true
console.log(set.values === set[Symbol.iterator]);  // true
console.log(set.keys() === set.values());          // false

// console.log prints them the same way
console.log(set.keys());                           // [Set Iterator] { 1, 2, '3' }
console.log(set.values());                         // [Set Iterator] { 1, 2, '3' }

// Set iterator does not equal itself
let keys1 = set[Symbol.iterator]();
let keys2 = set[Symbol.iterator]();
console.log(keys1 === keys2);                      // false

Per latest ECMAScript 2021 on Set.prototype.keys,

The initial value of the "keys" property is the same function object as the initial value of the "values" property.

This is the definition of Set.prototype.values() for point of comparison:

24.2.3.10 Set.prototype.values ( ) The following steps are taken:

  1. Let S be the this value.
  2. Return ? CreateSetIterator(S, value).

Question

Why is a set iterator not strictly equal to another set iterator generated in the same way from the same set object?

Ross Jacobs
  • 2,962
  • 1
  • 17
  • 27
  • 2
    `set.keys() === set.values()` will compare two different iterator **objects**. Two different **objects** are always different to each other. [A simplified example](https://jsbin.com/toqoqep/1/edit?js,console) which doesn't throw in sets as a red herring in all of this. – VLAZ Jan 30 '23 at 08:08
  • It wouldn't be logical if the returned iterator objects were the same. What if you already iterated over one entry in `.keys()` and then iterated over one entry in what you got from `.values()` - you wouldn't expect `.values()` to now return the second entry as first result, would you? So it doesn't make sense for them to share their state. – CherryDT Jan 30 '23 at 10:26
  • The link to the duplicate and VLAZ's comment are great resources, and thanks to all involved. I consider this question to be answered. – Ross Jacobs Jan 30 '23 at 12:11

0 Answers0