Skip to content

Instantly share code, notes, and snippets.

@gopal1996
Last active September 12, 2020 07:16
Show Gist options
  • Save gopal1996/6c03437560b3d64617588a5d35c21727 to your computer and use it in GitHub Desktop.
Save gopal1996/6c03437560b3d64617588a5d35c21727 to your computer and use it in GitHub Desktop.

Map

  • The Map object holds key-value pairs and remembers the original insertion order of the keys
  • Any value (both objects and primitive values) may be used as either a key or a value
const map = new Map([
    ['1', 'string'],
    [1, 'number'],
    [true, 'boolean']
]);

console.log(map);

OUTPUT:
Map(3) {"1" => "string", 1 => "number", true => "boolean"}

Map.prototype.set()

It adds the new element with a specified value at the end of the Map object

const map = new Map();

map.set('1', 'string');
map.set(1, 'number');
map.set(true, 'boolean');

console.log(map);

OUTPUT:
Map(3) {"1" => "string", 1 => "number", true => "boolean"}

We can also chain the set method as set method returns the map object.

const map = new Map();

map.set('1', 'string').set(1, 'number').set(true, 'boolean');

console.log(map);

OUTPUT:
Map(3) {"1" => "string", 1 => "number", true => "boolean"}

Map.prototype.get()

It returns the value by the key, if key doesn’t exist in map object it return undefined.

NOTE:

  • The regular Object will convert keys to string
  • Map keeps the type, so these two are different
const map = new Map();
map.set('1', 'string').set(1, 'number').set(true, 'boolean');

console.log(map.get('1'));      // Output: string
console.log(map.get(1));        // Output: number
console.log(map.get(true));     // Output: boolean
console.log(map.get('2'));     // Output: undefined
  • Map[key] isn’t the right way to use a Map
    • Although map[key] also works, e.g. we can set map[key] = 2, this is treating map as a plain JavaScript object, so it implies all corresponding limitations (no object keys and so on).

Always use map methods: set, get and so on

Map.prototype.size

It returns the number of elements in the Map

const map = new Map([
    ['1', 'string'],
    [1, 'number'],
    [true, 'boolean']
]);

console.log(map.size);  // Output: 3

Map.prototype.delete

It deletes an element with the specified key from the Map object

const map = new Map();

map.set('1', 'string').set(1, 'number').set(true, 'boolean');

map.delete('1');
console.log(map.size);          // Output: 2

Map.prototype.has

It returns true if the specified key is present in the Map object.

const map = new Map();

map.set('1', 'string').set(1, 'number').set(true, 'boolean');

console.log(map.has('1'));      // Output: true
console.log(map.has(2));        // Output: false
console.log(map.has(false));    // Output: false

Map.prototype.clear

It removes all the element from the Map object.

const map = new Map();

map.set('1', 'string').set(1, 'number').set(true, 'boolean');

map.clear();
console.log(map.size);          // Output: 0

Iteration over Map

Map.prototype.forEach

It executes the callback function once for every element in the Map, in the insertion order

let studentMap = new Map([
  ['Mike', 21],
  ['Tom', 24],
  ['Alex', 28]
]);

// looping over values (amounts)
studentMap.forEach(function(value){
    console.log(value)
})

Output:
21
24
28

Map.prototype.keys

Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.

let studentMap = new Map([
  ['Mike', 21],
  ['Tom', 24],
  ['Alex', 28]
]);

for (let name of studentMap.keys()) {
  console.log(name);
}

Output:
Mike
Tom
Alex

Map.prototype.values

Returns a new Iterator object that contains the values for each element in the Map object in insertion order.

let studentMap = new Map([
  ['Mike', 21],
  ['Tom', 24],
  ['Alex', 28]
]);

for (let age of studentMap.values()) {
  console.log(age);
}

Map.prototype.entries

Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order.

let studentMap = new Map([
  ['Mike', 21],
  ['Tom', 24],
  ['Alex', 28]
]);

for (let entry of studentMap) {
  console.log(entry);
}

Output:
["Mike", 21]
["Tom", 24]
["Alex", 28]
let studentMap = new Map([
  ['Mike', 21],
  ['Tom', 24],
  ['Alex', 28]
]);

console.log(studentMap.entries())

Output:
MapIterator {"Mike" => 21, "Tom" => 24, "Alex" => 28}

Map vs Object

Map Object
Key Types A Map's keys can be any value (including functions, objects, or any primitive). The keys of an Object must be either a String or a Symbol.
Key Order The keys in Map are ordered. Thus, when iterating over it, a Map object returns keys in order of insertion. The keys of an Object are not ordered
Size The number of items in a Map is easily retrieved from its size property. The number of items in an Object must be determined manually.
Iteration A Map is an iterable, so it can be directly iterated. Iterating over an Object requires obtaining its keys in some fashion and iterating over them.
Performance Performs better in scenarios involving frequent additions and removals of key-value pairs. Not optimized for frequent additions and removals of key-value pairs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment