Module: ES6+ Mastery

Maps/Sets

JavaScript Essentials: ES6+ Mastery - Maps & Sets

Maps and Sets are relatively new data structures introduced in ES6 (ECMAScript 2015) that provide powerful alternatives to traditional JavaScript Objects and Arrays when you need to store unique values or key-value pairs. They offer performance benefits and more intuitive APIs for specific use cases.

1. Maps

What are Maps?

A Map is a collection of key-value pairs where both keys and values can be of any data type (including objects, functions, and primitive types). This is a significant difference from regular JavaScript objects, where keys are typically strings or Symbols.

Key Features:

  • Any Data Type for Keys: Unlike objects, you can use any data type as a key.
  • Maintains Insertion Order: Maps remember the original order in which key-value pairs were added.
  • Size Property: Easily determine the number of entries with the size property.
  • Better Performance for Frequent Additions/Deletions: Generally faster than objects for these operations, especially with a large number of entries.
  • Iteration: Easy to iterate over entries using for...of loops or the forEach method.

Creating a Map:

// Empty Map
const myMap = new Map();

// Map with initial values (using an array of arrays)
const initialMap = new Map([
  ['name', 'Alice'],
  [1, 'Number One'],
  [{a: 1}, 'Object Value'] // Key is an object!
]);

console.log(initialMap); // Output: Map(3) { 'name' => 'Alice', 1 => 'Number One', {…} => 'Object Value' }

Map Methods:

Method Description Return Value
set(key, value) Adds a new key-value pair to the Map. The Map object
get(key) Retrieves the value associated with a key. The value, or undefined if the key doesn't exist.
has(key) Checks if a key exists in the Map. true or false
delete(key) Removes a key-value pair from the Map. true if the key existed and was deleted, false otherwise.
clear() Removes all key-value pairs from the Map. undefined
size Returns the number of key-value pairs. A number
forEach(callback, thisArg) Executes a provided function once for each key-value pair. undefined
keys() Returns an iterator of all the keys. An Iterator
values() Returns an iterator of all the values. An Iterator
entries() Returns an iterator of all [key, value] pairs. An Iterator

Example:

const myMap = new Map();
myMap.set('name', 'Bob');
myMap.set(123, 'Some Number');
myMap.set({a: 1}, 'Object Value');

console.log(myMap.get('name')); // Output: Bob
console.log(myMap.has(123));    // Output: true
console.log(myMap.size);       // Output: 3

myMap.delete(123);
console.log(myMap.size);       // Output: 2

myMap.forEach((value, key) => {
  console.log(`Key: ${key}, Value: ${value}`);
});

// Output:
// Key: name, Value: Bob
// Key: {a: 1}, Value: Object Value

2. Sets

What are Sets?

A Set is a collection of unique values. It automatically removes duplicate values. Like Maps, Sets can store values of any data type.

Key Features:

  • Unique Values: Sets only store each value once.
  • No Indexing: Values are not accessed by index like in arrays.
  • Size Property: Easily determine the number of unique values with the size property.
  • Efficient Membership Testing: Checking if a value exists in a Set is very fast.
  • Iteration: Easy to iterate over values using for...of loops or the forEach method.

Creating a Set:

// Empty Set
const mySet = new Set();

// Set with initial values (using an array)
const initialSet = new Set([1, 2, 2, 3, 4, 4, 5]); // Duplicates are removed

console.log(initialSet); // Output: Set(5) { 1, 2, 3, 4, 5 }

Set Methods:

Method Description Return Value
add(value) Adds a new value to the Set. The Set object
delete(value) Removes a value from the Set. true if the value existed and was deleted, false otherwise.
has(value) Checks if a value exists in the Set. true or false
clear() Removes all values from the Set. undefined
size Returns the number of unique values. A number
forEach(callback, thisArg) Executes a provided function once for each value. undefined
values() Returns an iterator of all the values. An Iterator
keys() Returns an iterator of all the values (same as values()). An Iterator
entries() Returns an iterator of all [value, value] pairs. An Iterator

Example:

const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // Duplicate - will not be added
mySet.add('hello');
mySet.add({a: 1});

console.log(mySet.size); // Output: 4
console.log(mySet.has(2)); // Output: true
console.log(mySet.has(3)); // Output: false

mySet.delete(2);
console.log(mySet.size); // Output: 3

mySet.forEach(value => {
  console.log(value);
});

// Output:
// 1
// hello
// {a: 1}

When to Use Maps and Sets

  • Maps:
    • When you need to associate arbitrary data types as keys with values.
    • When you need to maintain the order of insertion.
    • When you need to frequently add or delete key-value pairs.
  • Sets:
    • When you need to store a collection of unique values.
    • When you need to efficiently check for the existence of a value.
    • When you want to remove duplicate values from an array.

In summary: Maps and Sets are powerful additions to the JavaScript language, offering more flexibility and performance in specific scenarios compared to traditional Objects and Arrays. Understanding their strengths and weaknesses will help you write more efficient and maintainable code.