Javascript - Creating Maps
Code Life
By Pierre Marsaa
Pairing Keys and Values with a Map
Imagine tracking each trainer's score during a tournament: you want to link a trainer's name (the key) to their score (the value), and look up any score in an instant.
A Map is a collection designed specifically to store key → value pairs:
1.
Create an empty Map with new Map().
2.
Use .set(key, value) to store a pair.
3.
Use .get(key) to read the value linked to a key.
↗️
Loading editor...
↶
↷
Just like a Set, a Map tells you how many pairs it holds via .size. And if you call .get() with a key that doesn't exist, it simply returns undefined:
↗️
Loading editor...
↶
↷
Verify