Your Essential Guide To Map Built-in Object In Javascript
Tags: javascript, typescript, tutorial, webdev
Published: 2021-07-28 00:16:18

I'm [Aya Bouchiha](https://t.me/AyaBouchiha), today, we'll talk about Map built-in object.

## Definition of Map Built-in Object

Map: is a data structure that stores key-value pairs, Its keys can be any datatype(primitive, objects, functions). Additionally, The original order of elements is preserved.

## The advantages of Map

-   Flexible with keys, because they can be any type unlike Object (keys have to be strings and symbols)

-   Supports millions of items, 50% more than Object. A map can store 16.7 million key-value pairs where an Object can store 11.1.

-   getting easily and fastly the size of the map.

-   There are no default keys. Unlike objects that have default keys like _valueOf_

## Map Constructor

```javascript
const newMap = new Map();
const data = new Map([
	['key', 'value'],
	[{ username: 'AyaBouchiha', job: 'full-stack developer' }, 'Aya Bouchia'],
	[true, 'isDeveloper'],
	[
		function sayHello() {
			return 'hello';
		},
		'Hello World',
	],
]);
console.log(newMap);
console.log(data);
```

Ouput:

```javascript
Map {}
Map {
  'key' => 'value',
  { username: 'AyaBouchiha', job: 'full-stack developer' } => 'Aya Bouchia',
  true => 'isDeveloper',
  [Function: sayHello] => 'Hello World'
}
```

## Map.prototype.size

**size**: this Map property returns the number of items in a specified map.

```javascript
const newMap = new Map();
const data = new Map([
	['key', 'value'],
	[{ username: 'AyaBouchiha', job: 'full-stack developer' }, 'Aya Bouchia'],
	[true, 'isDeveloper'],
	[
		function sayHello() {
			return 'hello';
		},
		'Hello World',
	],
]);
console.log(newMap.size); // 0
console.log(data.size); // 4
```

## Map.prototype.get(key)

**get(key)**: is an instance method that lets you get a value of a specified key if it exists, otherwise, It returns _undefined_.

```javascript
const products = new Map([
	['phone', 500],
	['laptop', 1000],
	['mouse', 22],
]);
console.log(products['phone']); //! undefined
console.log(products.get('phone')); // 500
console.log(products.get('something-else')); // undefined
```

## Map.prototype.set(key, value)

**set(key, value)**: is an instance method that lets you set or update a value for a key in a Map object

```javascript
const users = new Map();
console.log(users); // Map { }
users.set('key', 'value');
users.set('aya', 'bouchiha');
console.log(users); // Map { 'key' => 'value', 'aya' => 'bouchiha' }
users.set('key', 'something'); // update the element that its key is 'key'
users['key'] = 'will not work!';
console.log(users.get('key')); // something
console.log(users.size); // 2
```

## Map.prototype.delete(key)

**delete(key)**: used to remove an item specified by a given key from a Map. It returns _true_ if the item exists, otherwise, The method returns _false_.

```javascript
const products = new Map([
	['phone', 500],
	['laptop', 1000],
	['mouse', 22],
]);

console.log(products.get('phone')); // 500
console.log(products.delete('phone')); // true
console.log(products.get('phone')); // undefined
console.log(products.delete()); // false
console.log(products.delete('nothing!')); // false (because key is not found)
```

## Map.prototype.clear()

**clear()**: this Map instance method deletes all key-value pairs which exist in the specified Map.

```javascript
const data = new Map([
	['key', 'value'],
	[{ username: 'AyaBouchiha', job: 'full-stack developer' }, 'Aya Bouchia'],
	[true, 'isDeveloper'],
	[
		function sayHello() {
			return 'hello';
		},
		'Hello World',
	],
]);

console.log(data.size); // 4
data.clear();
console.log(data.size); // 0
```

## Map.prototype.has(key):

**has(key)**: check if the given key exists in a specified Map.

```javascript
const products = new Map([
	['phone', 500],
	['laptop', 1000],
	['mouse', 22],
]);
console.log(products.has('laptop')); // true
console.log(products.has()); // false
products.set(undefined, 0);
console.log(products.has()); // true
console.log(products.has('nothing!')); // false
```

## Map.prototype.forEach(callback)

**forEach(callback, thisArg)**: Invokes a callback for each key/value pair in the specified Map. [more details](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach)

```javascript
const products = new Map([
	['phone', 500],
	['laptop', 1000],
	['mouse', 22],
]);

products.forEach((element) => console.log(element));
products.forEach((productPrice, productName) =>
	console.log(`you have to buy ${productPrice}$ to get a new ${productName}`),
);
```

Output:

```javascript
500
1000
22
'you have to buy 500$ to get a new phone'
'you have to buy 1000$ to get a new laptop'
'you have to buy 22$ to get a new mouse'
```

## Map.prototype.keys()

**keys()**: is a  method that returns a new **Iterator** object that contains the **keys** for each element in the specified Map.

```javascript
const products = new Map([
	['phone', 500],
	['laptop', 1000],
	['mouse', 22],
]);

const productsKeys = products.keys();
console.log(productsKeys.next()); //  { value: 'phone', done: false }
console.log(productsKeys.next().value); // laptop
console.log(productsKeys.next().value); //  mouse
console.log(productsKeys.next()); // { value: undefined, done: true }
```

## Map.prototype.values()

**values()**: is a  method that returns a new **Iterator** object that contains the **values** for each element in the specified Map.

```javascript
const products = new Map([
	['phone', 500],
	['laptop', 1000],
	['mouse', 22],
]);

const productsValues = products.values();
console.log(productsValues.next()); //  { value: 500, done: false }
console.log(productsValues.next().value); // 1000
console.log(productsValues.next().value); // 22
console.log(productsValues.next()); // { value: undefined, done: true }

```

## Map.prototype.entries()

**entries()**:returns an array(iterator) [key, val] for each element in the specified Map

```javascript
const products = new Map([
	['phone', 500],
	['laptop', 1000],
	['mouse', 22],
]);

const productsIterator = products.entries();
console.log(productsIterator.next()); //  { value: [ 'phone', 500 ], done: false }
console.log(productsIterator.next().value); // [ 'laptop', 1000 ]
console.log(productsIterator.next().value[0]); // mouse
console.log(productsIterator.next()); // { value: undefined, done: true }
```

### Summary

+ *size*: returns the number of items in a specified map.
+ *get(key)*: lets you get a value of a specified key if it exists, otherwise, It returns _undefined_.
+ *set(key, value)*: set or update a value for a key in a Map object.
+ *delete(key)*: used to remove an item specified by a given key from a Map. It returns _true_ if the item exists, otherwise, The method returns _false_.
+ *clear()*: deletes all key-value pairs which exist in the specified Map.
+ *has(key)*: check if the given key exists in a specified Map.
+ *forEach(callback, thisArg)*: Invokes a callback for each key/value pair in the specified Map. 
+ *keys()*:returns a new **Iterator** object that contains the **keys** for each element in the specified Map
+ *values()*: returns a new **Iterator** object that contains the **values** for each element in the specified Map.
+ *entries()*:returns an array(iterator) [key, val] for each element in the specified Map.

### References & Useful Resources

-   [Map vs Object](https://stackoverflow.com/questions/18541940/map-vs-object-in-javascript)

-   [Map Object mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)

-   [Map (w3schools)](https://www.w3schools.com/Js/js_object_maps.asp)


To Contact Me:

email:developer.aya.b@gmail.com
telegram: [Aya Bouchiha](https://t.me/AyaBouchiha)

Have a great day!