JavaScript

Last Updated: 2/2/2023

Maps

  • A Map is a collection key-value pairs where the keys and values can be any datatype.
  • A Map remembers the original insertion order of the keys.

Example

// Create a Map
const  courses = new  Map();

// Set Map Values
courses.set("1", "HTML");
courses.set("2", "CSS");
courses.set("3", "JS");

// Get Map Value
console.log(courses.get("1"));

// Update Map Value
courses.set("3", "Javascript");

Important Members

size: Returns the number of elements in a Map
set: Sets the value for a key in a Map
get: Gets the value for a key in a Map
delete: Removes a Map element specified by the key
has: Returns true if a key exists in a Map
forEach: Calls a function for each key/value pair in a Map
entries: Returns an iterator with the [key, value] pairs in a Map
courses.forEach((value, key) => console.log(value, key));

for(let entry of courses)
    console.log(entry);

console.log(courses.get("1"));

console.log(courses.size);

courses.delete("2");

console.log(courses.has("2"));

WeakMaps

  • The first difference between Map and WeakMap is that keys must be objects, not primitive values
  • If you use an object as the key in it, and there are no other references to that object, it will be removed from memory and from the map automatically.
  • It supports add, has and delete, but not size, keys() and no iterations.
let cache = new WeakMap();
let obj1 = { name: "page1" };
cache.set(obj1, "page1 content");

let obj2 = {name: "page2"}
cache.set(obj2, "page2 content");

obj1 = null;