Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EcmaScript6: strange behavior of console.log with WeakSet argument

How the following can be explained: if we comment first call to console.log, the set.[[Entries]].length will be 1, if one is not commented set.[[Entries]].length = 0;

Output: length = 0;

let mySet = new WeakSet(),
key = {};

mySet.add( key );           // add the object to the set

//console.log( mySet );     // uncommenting will change the [[Entries]].length
key = null;                 // delete key
console.log( mySet );       // [[Entries]].length: 0

Otput: length = 1

let mySet = new WeakSet(),
key = {};

mySet.add( key );           // add the object to the set

console.log( mySet );         // commenting will change the [[Entries]].length
key = null;                 // delete key
console.log( mySet );       // [[Entries]].length: 1

One more edition: if we add one more console.log( mySet ) in the 2nd case (to the end of script). [[Entries]].length will be 0.

One of commentors mentioned that it should be the garbage collector. But how it will behave in the real script? If I'll use one time calling the object (without second time) will it be deleted or not (after object will be setted to null)?

like image 668
Vadim Cherepenichev Avatar asked Jan 29 '26 06:01

Vadim Cherepenichev


1 Answers

This isn't strange at all, it's just the standard behaviour of weak collections. [[Entries]] is an internal slot, with very much implementation-dependent behaviour, and might not even exist in the actual implementation but just be shown in the debugger.

Once you overwrite the key reference to the object, it can get garbage-collected and won't be held by the mySet either. The custom behaviour of console.log apparently creates another reference to the object (as you can still interact with it in the console) so it is not garbage-collected, and still shows up in the list.

like image 139
Bergi Avatar answered Jan 30 '26 19:01

Bergi