Set and Map

Mateusz -

Set and Map were introduced in ES6 as new features.

Set

Similar to array-like. It enforces uniqueness for each item inside this Set and keeps the order of the inserted items no matter what.

Set methods

add() - Adds new item
delete() - removes new item
has() - checks if item exists
clear() - clears the set
forEach() - loops through items
entries/values - returns new iterator object

Set in action

//
const animals = new Set();

animals.add('monkey');
animals.add('rhino');
animals.add('rhino');

animals.forEach((item) => {
  console.log(item); //monkey //rhino
});

animals.delete('rhino'); //deletes rhino item

console.log(animals.has('monkey')); //return true

animals.clear(); //clears the set
//

Each item in the Set should be unique so we cannot add two identical values to our Set.

Map

A list of key values pairs, enforce uniqueness. Keeps the order of the inserted items no matter what. Differences between a normal object and a Map can be any data. In object keys will be always converted to strings.

Map methods

get(key) - return the item value
set(key, value) - adds new key-value pair
delete(key) - removes the item
has(key) - checks if item exists
forEach() - loops through items
clear() - clears the entire map
entries/keys/values - returns new iterator object

Map in action

//
const animals = new Map();

animals.set('shark', 'dangerous animal');
animals.set('dog', 'friendly animal');

animals.forEach((value, key) => {
 console.log(`${key} = ${value};`); //shark = dangerous animal; dog = friendly animal;
});

animals.delete('shark');

console.log(animals.has('shark')); //false, because we just deleted it

console.log(animals.get('dog')); // friendly animal

animals.clear(); //clears the map
//

Summary

Set and Maps give us a good opportunity to use them for simple or even complex data structures, where the use of objects or arrays can be problematic.