ES6 in Depth
  • Introduction
  • Installation
  • Block Scope
    • Constant
    • Use cases
  • Template String
    • New String Methods
    • Tagged Template Literal
  • New Number Methods
  • Arrow Function
    • Default Parameters
    • Lexical This Scope
    • Where not to use arrow function
  • Object Enhancement
  • New Array Methods
    • For Of
  • Spread Operator
  • Destructuring
    • Array Destructuring
  • Class
  • Symbols
  • New Data Structures
    • Set
    • Map
    • WeakSet
    • WeakMap
    • Iterators
    • Generators
  • Promise
  • Import Export
Powered by GitBook
On this page
  • WeakMap Use Case
  • WeakMap Demo

Was this helpful?

  1. New Data Structures

WeakMap

  • References to keys/values held weakly

  • Do not prevent garbage collection

  • Small api ( add, delete, check for values ) compared to set/map

  • cann't be iterated

  • Have no size as it does garbage collected

Note

  • keys must be objects

  • the values can be arbitrary values.

var wm = new WeakMap();
wm.add()
wm.delete()
wm.has()

WeakMap Use Case

let dog1 = {name: 'Tomy'};
let dog2 = {name: 'Tuffy'};

const strongMap = new Map();
const weakMap = new WeakMap();

strongMap.set(dog1, 'Tomy is the best');
weakMap.set(dog2, 'Tuffy is the best');

dog1 = null;
dog2 = null;

// strongMap.size => 1
// WeakMap.size => undefined
strongMap -> Map(1) {Object {name: "Tomy"} => "Tomy is the best"}
weakMap -> WeakMap {} // expected, as it garbage collected item in it, because dog1 reference is null now

WeakMap Demo

var wm = new WeakMap();
wm.set({name: 'hemant'}, 30).set({age: 20}, function(){ return 'your age'; })
console.log(wm); // WeakMap {Object {name: "hemant"} => 30, Object {age: 20} => function}
PreviousWeakSetNextIterators

Last updated 4 years ago

Was this helpful?