Category: javascript
map in javascript
Published on 09 Mar 2026
Explanation
In JavaScript, a Map is a built-in
object that stores key–value pairs.
Unlike normal
objects, Map allows keys of any type
(objects, functions, primitives)
a preserves insertion order.
Code:
const map = new Map();
map.set('name', 'Praveen');
map.set('age', 25);
map.set(1, 'Number Key');
console.log(map.get('name'));
Explanation
set() method adds or updates a
key-value pair in a Map.
get() method retrieves the value associated
with a specified key.
Code:
const map = new Map();
map.set('language', 'JavaScript');
map.set('version', 'ES6');
const map = new Map();
map.set('framework', 'React');
console.log(map.get('framework'));
Explanation
has() method checks whether a Map
contains a specific key.
delete() method removes a specific key-value
pair from the Map.
Code:
const map = new Map();
map.set('database', 'MongoDB');
console.log(map.has('database'));
console.log(map.has('sql'));
map.set('backend', 'Node.js');
map.delete('backend');
console.log(map.has('backend'));
Explanation
Clear()
method removes all key-value pairs
size
property returns the number of key-value
pairs in the Map.
Code:
const map = new Map();
map.set('a', 1);
map.set('b', 2);
map.clear();
console.log(map.size);
map.set('x', 10);
map.set('y', 20);
console.log(map.size);
Explanation
keys()
returns an iterator containing
all keys in the Map.
values()
returns an iterator containing
all values in the Map.
Code:
const map = new Map([
['name', 'hackforge'],
['course', 'fullstack']
]);
for (let key of map.keys()) {
console.log(key);
}
for (let value of map.values()) {
console.log(value);
}
Explanation
entries() method
an iterator containing
key-value pairs from the Map.
forEach()
executes a callback function for each
key-value pair in the Map.
Code:
const map = new Map([
['name', 'hackforge'],
['course', 'fullstack']
]);
for (let [key, value] of map.entries()) {
console.log(key, value);
}
map.forEach((value, key) => {
console.log(key + ': ' + value);
});