techStackGuru

Javascript map object


A Map object also retains the order in which the keys were first inserted. The Map object stores key-value pairs in which any type of value may be used as either a key or a value.


Declare

const mapObj = new Map();

Set values to map

mapObj.set('a', 1);
mapObj.set('b', 2);
mapObj.set('c', 3);

// Map { 'a' => 1, 'b' => 2, 'c' => 3 }

Get values from map

mapObj.get('a') // 1

Change value from map

mapObj.set('a', 5);
console.log(mapObj.get('a')); // 5

Delete value from map

mapObj.delete('b');
console.log(mapObj); // Map { 'a' => 5, 'c' => 3 }

Check size from map

console.log(mapObj.size); // 2

Check typeof of map

console.log(typeof(mapObj)); // object

Check instanceof map

console.log(mapObj instanceof Map); // true

Check if key is available in map

console.log(mapObj.has('a')); // true
console.log(mapObj.has('d')); // false

Clear all entries from map

const mapObj = new Map();

mapObj.set('a', 1);
mapObj.set('b', 2);
mapObj.set('c', 3);

console.log(mapObj); // Map { 'a' => 1, 'b' => 2, 'c' => 3 }
mapObj.clear();
console.log(mapObj); // Map {}

previous-button
next-button