Starbeamrainbowlabs

Stardust
Blog

Ecmascript 6 Features 9: Map

Welcome to the 9th postin my weekly ES6: Features series. Today, I will be taking a look at Map, and its counterpart, the WeakMap.

At the simplest level, a Map in Javascript is a set of key-value pairs. You can do things like this:

> var map = new Map();
undefined
> map.set("Sticky Swamp", { x: 5, y: 7 });
Map { 'Sticky Swamp' => { x: 5, y: 7 } }
> map.set("Frosty Mountain", { x: 3, y: 4 });
Map {
'Sticky Swamp' => { x: 5, y: 7 },
'Frosty Mountain' => { x: 3, y: 4 } }
> map.set("Piranha Pond", { x: 7, y: 2 });
Map {
'Sticky Swamp' => { x: 5, y: 7 },
'Frosty Mountain' => { x: 3, y: 4 },
'Piranha Pond' => { x: 7, y: 2 } }
> map.get("Frosty Mountain").x
3
> map.has("Treasure")
false
> map.has("Piranha Pond")
true

Maps can also be iterated. With a bit of destructuring wizardry, we can list the content of a map like this:

> for(var [ key, value ] of map) { console.log(`Name: ${key} Location: (${value.x}, ${value.y})`); }
Name: Sticky Swamp Location: (5, 7)
Name: Frosty Mountain Location: (3, 4)
Name: Piranha Pond Location: (7, 2

If you only want to iterate over the keys or the values, you can get an iterable object of them with .keys() and .values() respectively.

> for(var key of map.keys()) { console.log(key); }
Sticky Swamp
Frosty Mountain
Piranha Pond
undefined
> for(var key of map.values()) { console.log(key); }
{ x: 5, y: 7 }
{ x: 3, y: 4 }
{ x: 7, y: 2 }
undefined

Note that you can't use .forEach() or any related functions (such as .map() or .filter()) on this object, and it's contents doesn't show up in the developer tools either.

Another cool feature of Maps is that you can use anything is the key. This allows you to create empty objects (for example), like so:

> map = new Map();
Map {}
> a = {}
{}
> b = {}
{}
> a == b
false
> map.set(a, "this is a")
Map { {} => 'this is a' }
> map.set(b, "this is b");
Map { {} => 'this is a', {} => 'this is b' }
> map.get(a)
'this is a'
> map.get(b)
'this is b'

This probably won't make too much sense with a normal Map, but mixing this with the WeakMap leads to some powerful data storage mechanisms.

WeakMaps

The WeakMap is the cousin of the Map, and is largely the same, but with a few important differences. Firstly, it isn't iterable, and you can't get a list a keys from it either. If you need sa list of keys, you should maintain it yourself.

This means that if you are using objects as your keys (as described above), and you loose all the references to that object, the garbage collector can not only come and collect the object you lost all references to, but also the value that it was tied to in the WeakMap. This helps you to avoid memory leaks if you don't actually need to iterate over the map at any point.

> wmap = new WeakMap()
{}
> a = {};
{}
> b = {};
{}
> wmap.set(a, "This is a")
{}
> wmap.set(b, "This is b");
{}
> wmap.get(a)
'This is a'
> wmap.get(b)
'This is b'
> delete a
true
> wmap.get(b)
'This is b'
> wmap.get(a)
ReferenceError: a is not defined

In the example above, once we delete a, we also loose our only connection with the data that it was tied to in the WeakMap, allowing the garbage collector to come over and clean thing up for us.

Other than that, the WeakMap acts much the same as the Map - it has the same get(), set() and has() methods that the Map does.

That concludes the 9th post in this series (sorry it was rather late)! Next time, I will probably take a look at Set.

Tag Cloud

3d 3d printing account algorithms android announcement architecture archives arduino artificial intelligence artix assembly async audio automation backups bash batch blender blog bookmarklet booting bug hunting c sharp c++ challenge chrome os cluster code codepen coding conundrums coding conundrums evolved command line compilers compiling compression conference conferences containerisation css dailyprogrammer data analysis debugging defining ai demystification distributed computing dns docker documentation downtime electronics email embedded systems encryption es6 features ethics event experiment external first impressions freeside future game github github gist gitlab graphics guide hardware hardware meetup holiday holidays html html5 html5 canvas infrastructure interfaces internet interoperability io.js jabber jam javascript js bin labs latex learning library linux lora low level lua maintenance manjaro minetest network networking nibriboard node.js open source operating systems optimisation outreach own your code pepperminty wiki performance phd photos php pixelbot portable privacy problem solving programming problems project projects prolog protocol protocols pseudo 3d python reddit redis reference release releases rendering research resource review rust searching secrets security series list server software sorting source code control statistics storage svg systemquery talks technical terminal textures thoughts three thing game three.js tool tutorial twitter ubuntu university update updates upgrade version control virtual reality virtualisation visual web website windows windows 10 worldeditadditions xmpp xslt

Archive

Art by Mythdael