Map in javascript

by Biswa R

JavaScript

var myMap = new Map();

///as key1,key2,key3 are not diffened so only 1 key value is stored in Map
/// undefined is the key here
/// it gets set every time 
var key1,key2,key3;
// setting the values
myMap.set(key1, "value associated with key1");//undefined --> "value associated with key1"
myMap.set(key2, 'value associated with key2');//undefined --> "value associated with key2"
myMap.set(key3, 'value associated with key3');//undefined --> "value associated with key2"

console.log(myMap.get(key1));//output -->'value associated with key3'
console.log(myMap.get(key2));//output -->'value associated with key3'
console.log(myMap.get(key3));//output -->'value associated with key3'

//lets clear the map
myMap.clear();
console.log(myMap.get(key3));//undefined

//lets create a valid map
var key1 = "key1",key2="key2",key3="key3";
myMap.set(key1, "value associated with key1");//undefined --> "value associated with key1"
myMap.set(key2, 'value associated with key2');//undefined --> "value associated with key2"
myMap.set(key3, 'value associated with key3');//undefined --> "value associated with key2"

console.log(myMap.get(key1));//output -->'value associated with key3'
console.log(myMap.get(key2));//output -->'value associated with key3'
console.log(myMap.get(key3));//output -->'value associated with key3'

//lets get all the keys present in the Map
var mapIter = myMap.keys();

console.dir(mapIter);
console.log(mapIter.next().value); 
console.log(mapIter.next().value); 
console.log(mapIter.next().value);

//lets remove 1 key from the Map
myMap.delete(key1);

console.log(myMap.has(key1));//checks if the key exist in the map -- false in this case
console.log(myMap.has(key2));//checks if the key exist in the map -- true in this case

//get the values in interation
for (var [key, value] of myMap) {
  console.log(key + ' = ' + value);
}