3

Why does console.log display WeakSet as <items unknown>?

[13:37:11] [~] node
Welcome to Node.js v14.4.0.
Type ".help" for more information.
> let student1 = { name: 'James', age: 26 };
undefined
> let student2 = { name: 'Julia', age: 27 };
undefined
> const roster = new WeakSet([student1, student2]);
undefined
> console.log(roster);
WeakSet { <items unknown> }
undefined

Context: I came across below example on WeakSet in ES6.

let student1 = { name: 'James', age: 26 };
let student2 = { name: 'Julia', age: 27 };
const roster = new WeakSet([student1, student2]);
console.log(roster);

The example suggests it should print

WeakSet {Object {name: 'Julia', age: 27}, Object {name: 'Richard', age: 31}}

But in node v14.4.0 it prints

WeakSet { <items unknown> }
kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80
  • 1
    Where exactly did you find that example? The page you linked on MDN notes "*There is no list of current objects stored in the collection. WeakSets are not enumerable.*" – Bergi Jun 21 '20 at 18:28
  • @Bergi It's part of a [Udacity ES6 course](https://classroom.udacity.com/courses/ud356/lessons/1b997dce-e2ce-4246-b5ae-d39ca175f887/concepts/5c3fd7d7-66b4-4a9c-b61d-33dd85b8cc0e) I was looking at. It's a free course but I think the link only works if you're logged in. I was wondering the use case of WeakSet, and your [answer to another question](https://stackoverflow.com/questions/30556078/ecmascript-6-what-is-weakset-for) helped. Now I'm convinced I can't (and shouldn't) enumerate/loop through a WeakSet. Thanks. – kgf3JfUtW Jun 21 '20 at 18:38

1 Answers1

2

The node-js team decided that its hard to correctly implement that. Here is the issue: https://github.com/nodejs/node/issues/19001

So that mean that WeakSet work correctly BUT console.log will always output an empty WeakSet

If you still wanna inspect the WeakMap you can do that by using utils inspect:

const { inspect } = require('util');
let student1 = { name: 'James', age: 26 };
let student2 = { name: 'Julia', age: 27 };
const weakSet = new WeakSet([student1, student2]);
console.log(inspect(weakSet, { showHidden: true }));
Hexception
  • 722
  • 10
  • 25