Map vs object

by tammasr

JavaScript

//Javascript Object
/* const x = {} */;
const a = {num: 1};
const b = {num: 2};

/* x[a] = 'hello' */
/* x[b] = 'world' */
/* console.log(x[a]) */


// Map
const m = new Map()
m.set(a, 'h1llo')
m.set(b, 'world')
/* m.delete(b) */
console.log(m)


/* Iterating using "for of" which is not available in javascript objects */

for ([key, value] of m.entries()) {
console.log(key, value)
}

/* Convert map into an array */
const ary = [...m]
console.log(ary)

/* Why do we need weak maps*/
/*In the below example x should only live inside the block scope....but when you console.log map outside the scope it still shows up inside map....To prevent this we use WeakMaps*/
{
  let x = {
    k1: 'v1'
  }
  
  var map = new Map();
  map.set(x, 'hi')
}
console.log('map', map)

/* Weak maps */
{
	let x = {
  	k1: 'v1'
  }
  
  var weakmap = new WeakMap();
  weakmap.set(x, 'heyy')
}
console.log('weak map', weakmap)