Yukulélé
Yukulélé

Reputation: 17102

Why WeakSet can't be used with Symbol?

Why it's not possible to .add() a Symbol in a WeakSet?

var ws = new WeakSet();
var sym = Symbol();
ws.add(sym); //error

Upvotes: 1

Views: 116

Answers (1)

Jordan Running
Jordan Running

Reputation: 106077

Only objects can be WeakSet members, but a symbol is a primitive. If you really need to store a symbol in a WeakSet you can wrap it in an object:

let ws = new WeakSet();
let symbol = Symbol();
let wrapped = Object(symbol);
ws.add(wrapped);

Upvotes: 2

Related Questions