WeakMap is a type of Map where only Objects can be passed as keys. Primitive data types such as String, Number, Boolean, etc are not allowed.
let user = {};
let comment = {};
let mapSettings = new WeakMap();
mapSettings.set(user, "Sam");
mapSettings.set(comment, "Great Post!!!");
console.log(mapSettings.get(user)); // Return Sam
console.log(mapSettings.get(comment)); // Return Great Post!!!
You can't assign primitive data types as key.
let mapSettings = new WeakMap();
mapSettings.set("user", "Sam"); // Return Error - Invalid value used as weak map key
Other methods available are has() and delete().
console.log(mapSettings.has(user)); // Return true
console.log(mapSettings.delete(user)); // Return true
WeakMap is not iterable, therefore they can't be used with for...of.
No comments:
Post a Comment