JavaScript Map Builtin - HashMap Magic

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript Map Builtin - HashMap Magic

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Introduction

const nameToAge = new Map();
nameToAge.set('john', 25); // Map { 'john' => 25 }
nameToAge.set('jane', 28); // Map { 'john' => 25, 'jane' => 28 }
nameToAge.set('john', 26); // Map { 'john' => 26, 'jane' => 28 }
nameToAge.get('john'); // 26
nameToAge.get('jill'); // undefined

const countryToCapital = new Map([
['France', 'Paris'],
['Italy', 'Rome'],
['Australia', 'Canberra'],
]);
// Map { 'France' => 'Paris', 'Italy' => 'Rome', 'Australia' => 'Canberra' }

console.log(nameToAge instanceof Map); // true
console.log(countryToCapital instanceof Map); // true

Iterables

const prices = new Map([
['cucumber', 50],
['tomatoes', 35],
]);

for (const entry of prices.entries()) {
console.log(entry); // ['cucumber', '50'], ['tomatoes', '35']
}
for (const entry of prices) {
console.log(entry); // ['cucumber', '50'], ['tomatoes', '35']
}
console.log([...prices]); // [['cucumber', '50'], ['tomatoes', '35']]
console.log([...prices.keys()]); // ['cucumber', 'tomatoes']
console.log([...prices.values()]); // [50, 35]

const pricesCopy = new Map(prices);
console.log(pricesCopy); // Map { 'cucumber' => '50', 'tomatoes' => '35' }

Map Keys

const objAsMap = Object.create(null);
objAsMap['hi'] = 'hi';
objAsMap[Symbol('french')] = 'bonjour';
objAsMap[123] = 'salam';
objAsMap['123'] = 'hola';
objAsMap[{ name: 'John' }] = 'konnichiwa';
objAsMap[{ name: 'Jane' }] = 'namaste';
console.log(objAsMap);
// {
// 'hi': 'hi',
// [Symbol(french)]: 'bonjour',
// '123': 'hola',
// '[object Object]': 'namaste'
// }

const map = new Map();
map.set('hi', 'hi');
map.set(Symbol('french'), 'bonjour');
map.set(123, 'salam');
map.set('123', 'hola');
map.set({ name: 'John' }, 'konnichiwa');
map.set({ name: 'Jane' }, 'namaste');
console.log(map);
// Map {
// 'hi' => 'hi',
// Symbol(french) => 'bonjour',
// 123 => 'salam',
// '123' => 'hola',
// { name: 'John' } => 'konnichiwa',
// { name: 'Jane' } => 'namaste'
// }

Insertion Order is Preserved

const orders = [
['John', 'Burger'],
['Jane', 'Steak'],
['John', 'Salad'],
];

const ordersGrouped = new Map();
for (const [name, item] of orders) {
if (ordersGrouped.has(name)) { ordersGrouped.get(name).push(item); }
else { ordersGrouped.set(name, [item]); }
}
console.log([...ordersGrouped]);
// [
// ['John', ['Burger', 'Salad']],
// ['Jane', ['Steak']]
// ]

Methods and Properties

const balance = new Map();

balance
.set('John', 10)
.set('Jane', 18);

console.log(balance.get('John')); // 10
console.log(balance.get('Jill')); // undefined

balance.delete('John'); // true
balance.delete('Jill'); // false

balance.has('Jane'); // true
balance.has('Jill'); // false

console.log(balance); // Map { 'Jane' => 18 }
console.log(balance.size); // 1

balance.clear();
console.log(balance); // Map {}

Map to Object to Map

const countryToFlag = new Map([
['United States', '🇺🇸'],
['France', '🇫🇷'],
['Australia', '🇦🇺'],
]);

const obj = Object.fromEntries(countryToFlag);
console.log(obj);
// { United States: '🇺🇸', France: '🇫🇷', Australia: '🇦🇺' }

const map = new Map(Object.entries(obj));
console.log(map);
// Map(4) { 'United States' => '🇺🇸', 'France' => '🇫🇷', 'Australia' => '🇦🇺' }

Map Uses Strict Equality

const obj1 = { name: 'Alice' };
const obj2 = { name: 'Alice' };

console.log(obj1 === obj2); // false
console.log(obj1 === obj1); // true
console.log(obj2 === obj2); // true

const ageMap = new Map();
ageMap.set({ name: 'Alice' }, 20);
ageMap.set({ name: 'Alice' }, 21);

console.log(ageMap);
// Map { { name: 'Alice' } => 20, { name: 'Alice' } => 21 }

ageMap.clear();

const alice = { name: 'Alice' };
ageMap.set(alice, 20);
ageMap.set(alice, 21);

console.log(ageMap);
// Map { { name: 'Alice' } => 21 }

let personMap = new Map();
personMap.set('Alice', { name: 'Alice', age: 20 });
personMap.set('Alice', { name: 'Alice', age: 21 });

console.log(personMap);
// Map { 'Alice' => { name: 'Alice', age: 21 } }
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

Just like the set data structure that we've looked at. JavaScript comes with a built-in map class, which is a very effective constant time key to value lookup and maintain a status structure. And it really makes JavaScript very powerful modern programming language. We can create an instance of the map by using the new operator with a map constructor at score. A map is a key value store and the intent for this name to age is to have the person name as the key and the person age as the value. As an example, we can state that John is someone who has an age of 25 and then Jane is someone who has an age of 28. This map now has two keys, John and Jane,

00:38

with corresponding values of 25 and 28. Every key in the map needs to be unique, so if you want to update John's age because he's just had his birthday, we can do that by setting John into a new value of 26. Just like the set TE structure internally, map uses hashing to ensure constant time or fun reading and writing for any given key. We've done some writing using the set method and we can do some reading by using the GET method. So of course the current age for John is 26, so if we get John, that is the numeric value that we get.

01:11

If we try to get something that is not present within the map as an example, Jill has never been set so the JavaScript on time will give us a special value of undefined. In addition to providing values to the map by using the set method, we can also provide various to the map by passing an AL to the map constructor. Each item of the atrium must be a key value pair. And as an example, we are providing an array over here where each item in the array is a key value pair, like France is the key and Paris is the value. So essentially here we are creating a map with the values preset France pointing to Paris, Italy pointing to Rome and Australia pointing to Canberra.

01:48

Within JavaScript there is a convention of using the term entry for a key value pair. Just like any other class within JavaScript, we can use the instance of operator to check if a particular value is an instance of a map and of course a name to age and country to capital are both maps. Maps in JavaScript work nicely as intervals the map constructor accepts and interval of entries. The map itself is an interval of entries and it even comes with convenience methods to just iterate over the keys or the values. We already know how to create an instance of the map by using an interval of

02:21

entries like an array of entries. And here we have a map of prices with cucumber pointing to 50 and to tomatoes pointing to 35 map provides an entries method which returns an interval of entries. So here we can log the entries cucumber 50 and method 35. And in fact the map itself is also an iterable of entries, so we don't even need to invoke the entries method. We can simply loop through the entries of a map and just like any other iterable, we can also easily get the output as an array by using the spread operator. We can also iterate over just the keys of the map by using the keys method and

02:56

even just the values of the map by Using the values method. Now because the map itself is an interval of entries and it accepts an interval of entries in the constructor, we can actually create a copy of the map quite easily by just passing it to a new map constructor. So here prices copy will be a new map that contains the same key value pairs as the original map. Traditionally before we got a proper built-in map class, people used objects even for dynamic key value pairs. But in modern JavaScript for the key based lookup data structure, the map class provides a number of benefits over just using or rather abusing

03:32

an object. As we saw in our prototype lesson, we can create a clean object free from any standard object keys like two string by using object dot create now. And this does allow us to have strings as keys with values being whatever we want and even works with symbols reliably. But for any other type of key it can be pretty done unreliable. For example, if you set the number 1, 2, 3 to salam, it can get overwritten by the string. 1, 2, 3, hola. And if you try to use an object as a key, it is going to be completely useless. That is because all objects will get converted to the same string key.

04:07

So even though we are trying to set six different keys over here, we will only get four distinct keys in the final object. The map data structure, however has no such restrictions. You can use any value that you can assign to a variable as a key within a map. Let's create a new instance of the map and set high to high. Set a symbol to Bon Jo. Set a number to salam, set a string. 1, 2, 3 to hola, set an object to K and a different object to namaste. And if you log out the map, it has all of these keys and all of these values without fighting with one another. So the guidance is pretty simple.

04:43

If you need an object with a known structure with only identify friendly or string keys, use an object. But if you need a dynamic key value data structure, use the map instead. The JavaScript map always preserves insertion order and this can greatly simplify any complicated sequence preservation requirement. When processing data, consider a simple array of entries where we have different orders as they come in. John place an order for a burger. Jane placed an order for a steak and then John placed an order for a salad. Your mission should choose to accept it is to consolidate the values under the

05:17

same name and to make sure that whoever placed the order first continues to be first in the queue. We can create a grouping of these quite easily by using a JavaScript map. We simply loop to the entries present within the orders, collect the name and the item and check if it already exists within the map. If it does, then we get the array by that name and push this item into that array. Otherwise, this is the first time we have seen this name and we simply set the name key within the orders to an array of that individual item. Once this loop terminates,

05:48

we should have all of the items grouped by the name pointing to the array of the items that the person has ordered. And because the insertion order is preserved, John will appear before Jane. Just like the set structure, the map class has a very laser-focused utility and therefore a very easy a p i to master with just a handful of properties and methods. We create a very simple map to keep track of who owes us how much money we've used a set method before, but what you might not know is that we can actually change the set calls because it is a fluent a p i.

06:21

So here we are saying that John owes us 10 and Jane owes us $18. Another method that we've already looked at is the get method, which can be used to get a value for a particular key. And if that key is present then the value is returned. And if that key does not exist within the map, then it returns undefined. We can remove items from the map by using the delete method. So if John manages to pay us back, we can remove him by using delete John. The delete method will also return true if that key did exist within the map. And since John did indeed exist, we get back through. However, if we invoke it with something that does not exist within the map,

06:56

it will still pass. However, it'll return the value false to indicate that Jill never owe us any money. We can also check if a particular key exists within the map by using the has method. So has Jane will be true and has Jill will be false. Now, right now there is only one person that owes us any money and it is Jane who owes us $18 and we can see how many items exist within the map by using the size property. Since it's just Jane, we get back the numeric one. We can also remove all keys and corresponding values from the map by using the clear method. And of course once we've invoked that,

07:30

this map will be empty because objects are such a critical part of the core of the programming language. Scape comes with built-in convenience methods to convert from an object to a map or convert from a map into an object. We create a simple map country to flag with some countries, United States, France, and Australia with their corresponding flag emojis. We know that a map is an iterable of entries and we can actually create an object from such an iterable by using the JavaScript built-in method object from entries. So this object will have the properties, United States, France, and Australia with the corresponding values being the flag emojis.

08:08

Just like the JavaScript built in object form entries takes an iterable of entries and returns an object. There is a built-in JavaScript method called object entries that takes an object and returns an array of entries. And since we already know that a map constructor will happily take an array of entries and create a map, we can use the chain object entries followed by a map constructor to convert an object into a corresponding map. So here we have a map that is functionally equivalent to the country to flag map that we originally started with.

08:40

A key thing to remember about the map data structure is that keys are checked using strict equality and this can impact your decision on what you want to use as a key and what you want to use as a value. We already know about JavaScript object equality. Just because we have two objects that are structurally equivalent, they will not be strictly equal because they are distinct instances only object one will be equal to object one and object two will be equal to object two. So if we try to create an age map and set an object with the name Alice to the age 20 and on her birthday we decide to create another object with the name

09:15

Alice and update the value to the age 21. We have made a mistake. We have made a map that has two objects, both with the name Alice with the ages 20 and then 21. There is nothing stopping you from using objects his keys, and in fact we can still do that quite easily. We just have to make sure that we use the same object every single time we update the value. So here we are storing the LS object into a simple variable and we make sure that we use that every single time we are setting the age. So now when we look at age map, it only has one object as the key with the value. Now updated to 21,

09:50

making sure that you store a reference to the object before you start using it into a variable can definitely become inconvenient. So another solution would be to rethink how we structure our map. Ideally think of some string or a number property that exists on the map that you can use as a key instead for our simple object, it seems that the string LSS is quite important, so we will use that as a key. Instead, we store an object against the key LSS and we just provide a new object whenever we want to modify any property. So now after the two calls, the person map will consist of a single entry with the key LSS pointing to the

10:24

object that has the name Ellis and the age 21. I hope you enjoyed this comprehensive tutorial on the built-in JavaScript map class. As always, thank you for joining me and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36