I'm storing objects references inside my JavaScript Sets:
let set1 = new Set();
let obj = {};
console.log(set1.size) //it returns 1
console.log(set1.has(obj)) //it returns true
obj = null;
console.log(set1.size); //it returns 1 because they are Hard Sets.
console.log(set1.has(obj)); //it returns false
In the last line, why does it return false if the size is not changed?
It returns size = 1
because it still holds one value (a reference to that object).
It returns false
because it does not has a value that is equals to null
.
But, if I remove the reference of the object using the next code:
You just overwrite a value of the variable. After that there is still one reference to the object left (inside the Set).
To remove an element from a Set
you need to use Set.prototype.delete()
method:
set1.delete(obj);
Presumably you need to do that while obj
still holds a reference to the object.