---
date: 2020-10-12
id: 0ad60ce3-4e34-490e-a565-a0ce330e6fc8
title: JavaScript Maps
---

# Description

For sane people [ES6](20201030093404-es6) comes with a <s>half assed
"solution"</s> handy data structure called `Map` which prevents the diy
shenanigans below.

# Syntax

## Basic operation

### Single entries

``` javascript
const map = new Map();
const KEY = {};

map.set(KEY, 123);
console.log(map.get(KEY)); // 123

console.log(map.has(KEY)); // true

map.delete(KEY);
console.log(map.has(KEY)); // false
```

### Array

``` javascript
const map = new Map([
    [ 1, 'one' ],
    [ 2, 'two' ],
    [ 3, 'three' ],
]);
```

## Iteration

### Keys

``` javascript
const map = new Map([
    [false, 'no'],
    [true,  'yes'],
]);

for (const key of map.keys()) {
    console.log(key);
}
```

### Values

``` javascript
const map = new Map([
    [false, 'no'],
    [true,  'yes'],
]);

for (const value of map.values()) {
    console.log(value);
}
```

### Entries

``` javascript
const map = new Map([
  [false, "no"],
  [true, "yes"],
]);

for (const entry of map.entries()) {
  console.log(entry[0], entry[1]);
}
```

### Converting to Arrays

The [spread](20201014094144-spread) operator (…) can turn an
[iterable](20201014092625-javascript_iterables) into an
[Array](20200826201029-arrays)

``` javascript
const map = new Map().set(false, 'no').set(true, 'yes');
console.log([...map.keys()]) // false, true
```

``` javascript
const map = new Map().set(false, 'no').set(true, 'yes');
console.log([...map])
```
