Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

331
Visualizações
Why can WeakMap and WeakSet work with 1 element, but cannot work with the whole data collection at once?

I've read that WeakMap and WeakSet don't support working with the entire data collection at once, which means that keys(), values(), entries(), size() and loops are inaccessible for these type of collections. It's written that the reason of that behaviour is that the developer cannot know exact moment when the garbage collector will work.

The source

...technically it’s not exactly specified when the cleanup happens. The JavaScript engine decides that. It may choose to perform the memory cleanup immediately or to wait and do the cleaning later when more deletions happen.

How do I see this? For example, the first element in the WeakMap/WeakSet data collection has been removed. But it may happen that the garbage collector hasn't cleared it from the storage yet. Hence, deleted element can be used in loops, methods that work with whole collection. To avoid this behaviour, all of these methods and loops aren't supported by these data collections.

let weakMap = new WeakMap();
let obj = {};
//adding some elements
weakMap.set(obj, 255);
weakMap.set({name: `Rita`}, `Rita`);
//deleting the first element
obj = null;

//we can't use loops for the whole collection 
//why? because deleted element with `obj` key can still exist in data storage
weakMap.get(obj); //it's theoretically possible that deleted element with `obj` key still 
//exists in the data storage, garbage collector hasn't reached it yet 

It's completely understandable. But what about referring to a single element? By the way, it's completely allowed for these type of collections. But, in fact, we also don't know exact moment when the garbage collector will work. As I see, it means that element can be deleted, but because of the fact that garbage collector hasn't reached it yet, it still can be displayed.

It turns out that limited functionality of these collections cannot secure bugs in the form of output of deleted elements? Am I correct?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda