{

ES6 Map Class Tutorials in Javascript Examples Typescript


Es6 Map Class

The map is one of the new classes introduced in the Es6 version. Other Classes are Set , WeakSet and WeakMap

The map is a data structure with keys and values. Keys can be any arbitrary value and values can be an object or primitive type.

Keys can be a Primitive types like Strings, Numbers, Symbols, Functions, Objects, and Dates.

We can implement a hashmap using the map in javascript and Typescript. It is ordered for insertion based.

Typescript has no built-in classes supported for Map, But Typescript supports the same data structure that ES6 supports.

Es6 classes can be used in typescript with configuring Es6 library in typescript configuration. In the tsconfig.json file, add “lib”: [“es6”] or you can add polyfill.js for this classes. This example mentioned will work in Typescript and Javascript. Syntax

let/var map=new Map()
or
let/var  map=new Map([iterablecollection])

Example

var map = new Map()
map.set(new Date(), function currentTime () {})
map.set(() => 'key', { objectkey: 'objectvalue' })
map.set(Symbol('symbol'), [6, 21])
console.log(map)

output is

0:{Fri Aug 31 2018 11:10:15 GMT+0530 (India Standard Time) => function currentTime() {}}
1:{key:() => 'key' value:{objectkey: "objectvalue"}}
2:{key:Symbol(symbol) value:(2) [6, 21]}

Map object created with a passing object during object creation. Object should contains iterable collection which outputs -[[‘key’, ‘value’], [‘key’, ‘value’]].

var map = new Map([
  ["key1", "value1"],
  ["key2", "value2"]])
  console.log(map) //{"key1" => "value1", "key2" => "value2"}

Adding elements to Map using the set method

Map objects can be created and added elements using Set() method

var map = new Map()
map.set('k', 'v')
map.set('k1', 'v1')
console.log(map) //{"k" => "v", "k1" => "v1"}

Methods

Let us create Map using the new Operator.

let map=new Map()

Method

Description

Example

Set(key,value)

Adding key and value to Map

map.set("key1", "value");
map.set("key2", "value2");
console.log(map.size) // 2

get(key)

Get the element for the given key. returns Undefined, if the key does not exist.

console.log(map.get("key1")) // value1

has(key)

return true - if the key exists in Map, else false.

console.log(map.has("key1")) // true
console.log(map.has("key45")) // false

delete(key)

Delete key and value for a given key from Map.

console.log(map) // {"key1" => "value1", "key2" => "value2"}
console.log(map.delete("key1")) // returns true if deleted
console.log(map.delete("key1231")) // returns false if key doest not exist
console.log(map) //{"key2" => "value2"}

clear()

Remove all keys and values of a Map.

console.log(map) // {"key1" => "value1", "key2" => "value2"}
map.clear()// returns nothing
console.log(map) //{}

size

Return size of Map.

console.log(map) // {"key1" => "value1", "key2" => "value2"}
console.log(map.size) //2

keys()

Return keys with an iterable collection of Map.

for (let key of map.keys()) {
    console.log(key);                   //key1 key2
}

values()

Return values with an iterable collection of Map.

for (let value of map.values()) {
    console.log(value);                   //value value2
}

entries()

Return keys and values with an iterable collection of Map.

//map entries iteration
for (let entry of map.entries()) {
    console.log(entry[0], entry[1]);    //key1 value  key2 value2
}

forEach(calback,args)

This is another way of doing iteration. Each element is applied with function execution.

 map.forEach(function(value,key){
      console.log(key, value);   //key1 value  key2 value2
 });

Map Usage Example

let map = new Map();
map.set("kiran", "35");
map.set("john", "50");
map.set("tom", "45");
//map size returns
console.log(map.size);//3
//map has
console.log(map.has('kiran'));//true
console.log(map.has('asdfasd'));//false
//map keys Iteration
for (let key of map.keys()) {
console.log(key);                   //kiran john tom
}
//map values iteration
for (let value of map.values()) {
console.log(value);                 //35 50 45
}
//map entries iteration
for (let entry of map.entries()) {
console.log(entry[0], entry[1]);    //kiran 35 john 50 tom 45
}
//object destructuring
for (let [key, value] of map) {
console.log(key, value);   //kiran 35 john 50 tom 45
}
//Map forEach Iteration
map.forEach(function(value,key){
console.log(key, value); //kiran 35 john 50 tom 45
});

Map SameValueZero Example Keys in Map checked using SameValueZero algorithm. SameValueZero is like === operator check with few diferences

NaN is not equal to NAN +0 is equal to -0


const map = new Map()
map.set(NaN, 'testvalue')
console.log(map.get(NaN)) // 'testvalue
map.set(-0, 54);
console.log(map.get(+0)) // 54
console.log(NaN === NaN) // false
console.log(+0 === -0) // true

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.