In this tutorial, you will learn about JavaScript Maps and WeakMaps with the assistance of examples.
In this article, you will learn-
- 1 Introduction
- 2 Create JavaScript Map
- 3 Insert Item to Map
- 4 Access Map Elements
- 5 Check Map Elements
- 6 Removing Elements
- 7 JavaScript Map Size
- 8 Iterate Through a Map
- 9 Iterate Over Map Keys
- 10 Iterate Over Map Values
- 11 Get Key/Values of Map
- 12 JavaScript Map vs Object
- 13 JavaScript WeakMap
- 14 WeakMap Methods
- 15 WeakMaps Are Not iterable
Introduction
In a ton of code, you’ll be writing as a prospective JS master, you’ll be iterating over arrays. Now and again, you’ll need to apply a change to the elements in the array. We can do this using for loops, yet writing the entirety of that stuff gets repetitive after or later. Let’s create our own helper method called map() to make things a little easier!
The JavaScript ES6 has presented two new data structures, i.e Map and WeakMap.
The map is like objects in JavaScript that allows us to store components in a key/value pair.
The components in a Map are inserted in an insertion order. In any case, in contrast to an object, a map can contain objects, functions and other data types as key.
Create JavaScript Map
To create a Map, we use the new Map(), constructor. For example,
// create a Map const map1 = new Map(); // an empty map console.log(map1); // Map {}
Insert Item to Map
After you create a map, you can use the set() technique to insert elements to it. For instance,
// create a set let map1 = new Map(); // insert key-value pair map1.set('info', {name: 'Salman', age: 26}); console.log(map1); // Map {"info" => {name: "Salman", age: 26}}
You can likewise use objects or functions as keys. For instance,
// Map with object key let map2 = new Map(); let obj = {}; map2.set(obj, {name: 'Salman', age: "26"}); console.log(map2); // Map {{} => {name: "Salman", age: "26"}}
Access Map Elements
You can access Map elements using the get() method. For example,
let map1 = new Map(); map1.set('info', {name: 'Salman', age: "26"}); // access the elements of a Map console.log(map1.get('info')); // {name: "Salman", age: "26"}
Check Map Elements
You can use the has() strategy to check if the element is in a Map. For instance,
const set1 = new Set([1, 2, 3]); let map1 = new Map(); map1.set('info', {name: 'Salman', age: "26"}); // check if an element is in Set console.log(map1.has('info')); // true
Removing Elements
You can use the clear() and the delete() strategy to eliminate components from a Map.
The delete() strategy returns true if a predetermined key/value pair exists and has been removed or, more than likely returns false. For instance,
let map1 = new Map(); map1.set('info', {name: 'Salman', age: "26"}); // removing a particular element map1.delete('address'); // false console.log(map1); // Map {"info" => {name: "Salman", age: "26"}} map1.delete('info'); // true console.log(map1); // Map {}
The clear() method removes all key/value pairs from a Map object. For example,
let map1 = new Map(); map1.set('info', {name: 'Salman', age: "26"}); // removing all element map1.clear(); // false console.log(map1); // Map {}
JavaScript Map Size
You can get the number of elements in a Map using the size property. For instance,
let map1 = new Map(); map1.set('info', {name: 'Salman', age: "26"}); console.log(map1.size); // 1
Iterate Through a Map
You can iterate through the Map components using the for…of loop or forEach() technique. The components are accessed in the insertion request. For instance,
let map1 = new Map(); map1.set('name', 'Salman'); map1.set('age', '27'); // looping through Map for (let [key, value] of map1) { console.log(key + '- ' + value); }
Output
name- Salman age- 27
You could also get the same results as the above program using the forEach() method. For example,
// using forEach method() let map1 = new Map(); map1.set('name', 'Salman'); map1.set('age', '27'); // looping through Map map1.forEach(function(value, key) { console.log(key + '- ' + value) })
Iterate Over Map Keys
You can iterate over the Map and get the key using the keys() technique. For instance,
let map1 = new Map(); map1.set('name', 'Salman'); map1.set('age', '27'); // looping through the Map for (let key of map1.keys()) { console.log(key) }
Output
name age
Iterate Over Map Values
You can iterate over the Map and get the values using the values() technique. For instance,
let map1 = new Map(); map1.set('name', 'Salman'); map1.set('age', '27'); // looping through the Map for (let values of map1.values()) { console.log(values); }
Output
Salman 27
Get Key/Values of Map
You can iterate over the Map and get the key/value of a Map using the entries() technique. For instance,
let map1 = new Map(); map1.set('name', 'Salman'); map1.set('age', '27'); // looping through the Map for (let elem of map1.entries()) { console.log(`${elem[0]}: ${elem[1]}`); }
Output
name: Salman age: 27
JavaScript Map vs Object
Map | Object |
Maps can contain objects and other data types as keys. | Objects can only contain strings and symbols as keys. |
Maps can be directly iterated and their value can be accessed. | Objects can be iterated by accessing its keys. |
The number of elements of a Map can be determined by size property. | The number of elements of an object needs to be determined manually. |
Map performs better for programs that require the addition or removal of elements frequently. | Object does not perform well if the program requires the addition or removal of elements frequently. |
JavaScript WeakMap
The WeakMap is like a Map. In any case, WeakMap can just contain objects as keys. For instance,
const weakMap = new WeakMap(); console.log(weakMap); // WeakMap {} let obj = {}; // adding object (element) to WeakMap weakMap.set(obj, 'hello'); console.log(weakMap); // WeakMap {{} => "hello"}
At the point when you attempt to add other data types other than objects, WeakMap throws an error. For instance,
const weakMap = new WeakMap(); // adding string as a key to WeakMap weakMap.set('obj', 'hello');
// throws error // TypeError: Attempted to set a non-object key in a WeakMap
WeakMap Methods
WeakMaps have methods get(), set(), delete(), and has(). For example,
const weakMap = new WeakMap(); console.log(weakMap); // WeakMap {} let obj = {}; // adding object (element) to WeakMap weakMap.set(obj, 'hello'); console.log(weakMap); // WeakMap {{} => "hello"} // get the element of a WeakMap console.log(weakMap.get(obj)); // hello // check if an element is present in WeakMap console.log(weakMap.has(obj)); // true // delete the element of WeakMap console.log(weakMap.delete(obj)); // true console.log(weakMap); // WeakMap {}
WeakMaps Are Not iterable
Unlike Maps, WeakMaps are not iterable. For example,
const weakMap = new WeakMap(); console.log(weakMap); // WeakMap {} let obj = {}; // adding object (element) to WeakMap weakMap.set(obj, 'hello'); // looping through WeakMap for (let i of weakMap) { console.log(i); // TypeError }
JavaScript Map and WeakMap were introduced in ES6. Some browsers may not support their use. To learn more, visit JavaScript Map support and JavaScript WeakMap support.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.