Show List

Maps and Sets

Maps and Sets are two data structures introduced in ES6 (ECMAScript 2015) that provide alternatives to objects and arrays with some unique characteristics.

Maps:

Maps are collections of key-value pairs where both keys and values can be of any data type. Unlike objects, keys in a map can be any value, including objects, functions, and primitive values. Here's how you can use maps:


// Creating a new Map const myMap = new Map(); // Adding key-value pairs to the map myMap.set('name', 'John'); myMap.set(1, 'One'); myMap.set(true, 'True'); // Getting values from the map console.log(myMap.get('name')); // Output: John console.log(myMap.get(1)); // Output: One console.log(myMap.get(true)); // Output: True // Checking if a key exists in the map console.log(myMap.has('name')); // Output: true // Deleting a key-value pair from the map myMap.delete('name'); // Iterating over the map myMap.forEach((value, key) => { console.log(`${key}: ${value}`); }); // Output: // 1: One // true: True

Maps maintain the insertion order of elements, and keys can be iterated in the order they were added. Maps also provide built-in methods to get the size of the map and to clear all key-value pairs.

Sets:

Sets are collections of unique values, where each value can occur only once. Sets are useful for storing unique values and performing operations like intersection, union, and difference. Here's how you can use sets:


// Creating a new Set const mySet = new Set(); // Adding values to the set mySet.add(1); mySet.add(2); mySet.add(3); mySet.add(1); // Adding duplicate value (ignored) // Checking if a value exists in the set console.log(mySet.has(1)); // Output: true // Deleting a value from the set mySet.delete(2); // Iterating over the set mySet.forEach(value => { console.log(value); }); // Output: // 1 // 3

Sets automatically remove duplicate values, making them useful for handling collections of unique elements. Sets also provide methods to get the size of the set and to clear all elements.

In summary, Maps and Sets are powerful data structures in JavaScript that provide efficient ways to store and manipulate collections of data, with Maps offering key-value pairs and Sets offering unique values. They provide additional flexibility and functionality compared to traditional objects and arrays in certain scenarios.



Next: Classes


    Leave a Comment


  • captcha text