Learn to create, get and set values in Map data structure in Javascript

Let's create a map using array of key, value pairs. Example,

// create a Map
const authorMap = new Map([
  ['name', 'Param Harrison'],
  ['age', 30],
  [('occupation', 'Author at JS Mates')]

Let's get the values from the Map using key,

// Get Name from the map
console.log(authorMap.get('name')); // Param Harrison

Setting a value in the map will be,

// set Age to the map
console.log('Old age -> ', authorMap.get('age')); // 30
authorMap.set('age', 20);
console.log('New age -> ', authorMap.get('age')); // 20

What will happen if you try to get a non-existing key?

// firstName key non-existing in the Map
console.log(authorMap.get('firstName')); // Output - undefined

Let's try to set the non-existing key,

// Set firstName
authorMap.set('firstName', 'Param');
console.log(authorMap.get('firstName')); // Output - Param

It will add the key and set the value to the Map. So if you need to add new key, alue pair, you just need to set it using set method.

You can play around with the code in codesandbox,