Javascript Map()

Map – object that stores key:value pairs (can be objects, primitive values, or combo of the two)

Creates an empty Map
const employee = new Map();

Adds key:value pair

if the key already exists, it will overwrite the existing key:value pair
employee.set('', {
firstName: 'James',
lastName: 'Parkes',
role: 'Content Developer'

Deletes a key:value pair. Returns true if successful, false it no

Removes all key:value pairs

Passing a key to check if a key:value pair is present

Passing a key to retrieve values

.keys() and .values() can be used to create an iterable object which can be looped through using next().
let iteratorObjForKeys = members.keys();
creates iterator object and stores the keys in a variable;
Uses .next() to loop through the keys
Object {value: 'Evelyn', done: false}
What is returned. “done” will return false until end of keys.

Can use .values() to do the same thing, just return values instead.
let iteratorObjForValues = memebers.values();;

Can also loop through Map using a for..of loop
for (const memeber of memebers) {

['Evelyn', 75.68]
['Liam', 20.16]

With a For..of loop, you get back an array with the first value being the key and the second being the value.

To print the key and value, you’ll need to use array destructuring
for (const member or members){
const [x, y] = memeber;
console.log(x, y);

You can also loop through a Map using .forEach()
members.forEach((value, key)) => console.log(key, value);

WeakMaps can only contain objects as keys, do not have a .clear() method and cannot be looped over.
let book1 = { title: 'Pride and Prejudice', author: 'Jane Austen'};
let book2 = { title: 'The Catcher in the Rue', author: 'J.D. Salinger'};
let book3 = { title: 'Gullivers Travels', author: 'Jonathan Swift'};
const library = new WeakMap();
library.set(book1, true);
library.set(book2, false);
library.set(book3, true);

To delete an object from a WeakSet, you have to set the object to null. Then JS’s garbage collectors frees up the memory that object used.
book1 = null;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.