2

" I'm working on WeakMap and WeakSet I'm trying to delete the object using null but still object is not deleted"

WeakMap:-

const book1 = { title: 'Pride and Prejudice', author: 'Jane Austen' };
const book2 = { title: 'The Catcher in the Rye', author: 'J.D. Salinger' };
const book3 = { title: 'Gulliver’s Travels', author: 'Jonathan Swift' };

const library = new WeakMap();
library.set(book1, true);
library.set(book2, false);
library.set(book3, true);

book1 = null;
console.log(library);

WeakSet:-

let student1 = { name: 'James', age: 26, gender: 'male' };
let student2 = { name: 'Julia', age: 27, gender: 'female' };
let student3 = { name: 'Richard', age: 31, gender: 'male' };

let roster = new WeakSet([student1, student2, student3]);
console.log(roster);


student3 = null;
console.log(roster);

I expected to delete the object using "null" but still getting the null objects onto the data structure.

haider ali
  • 21
  • 1
  • 6
  • 1
    I recommend reading up on JavaScript Garbage collection. You cannot, as far as I know, make guarantees about when a garbage collection will take place. Until one does, your weakmap or weakset will still retain the nullified value. – Alex Hart Jul 21 '19 at 03:11
  • I am assuming objects are only removed when garbage collection happens. No idea if that can forced. – Thilo Jul 21 '19 at 03:12
  • 1
    are you getting error Assignment to constant variable for book1 ? you can not reassign to a const – debugmode Jul 21 '19 at 03:13
  • @debugmode yes I get an error with const, but I also test with let – haider ali Jul 21 '19 at 03:19

0 Answers0