A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-map/ below:

Map in JS - GeeksforGeeks

Map in JS

Last Updated : 11 Feb, 2025

A Map is a data structure that stores key-value pairs, where each key is unique. It is similar to an object but has some advantages:

Creating a Map

Map() constructor allows two ways to create a Map in JavaScript.

JavaScript
let myMap = new Map();
let anotherMap = new Map([
    ['name', 'GFG'],
    ['age', 30],
    ['city', 'Noida']
]);
console.log(anotherMap);

Output
Map(3) { 'name' => 'GFG', 'age' => 30, 'city' => 'Noida' }
Properties of JavaScript Map

Example demonstrating all the common operations on a Map

JavaScript
// Create a new Map
const myMap = new Map();

// 1. set(key, value)
myMap.set('name', 'GFG');
myMap.set('age', 25);
myMap.set(1, 'One'); 

console.log(myMap);


// 2. get(key)
console.log(myMap.get('name')); 
console.log(myMap.get('age')); 
console.log(myMap.get(1)); 
console.log(myMap.get('invalidKey')); 

// 3. has(key)
console.log(myMap.has('name'));
console.log(myMap.has('address')); 
console.log(myMap.has(1)); 

// 4. delete(key)
myMap.delete('age');
console.log(myMap.has('age')); 
console.log(myMap);

// 5. clear()
myMap.clear();
console.log(myMap); // Output: Map {}

console.log(myMap.size); 

myMap.set('a', 1);
myMap.set('b', 2);
console.log(myMap.size); 
console.log(myMap);

Output
Map(3) { 'name' => 'GFG', 'age' => 25, 1 => 'One' }
GFG
25
One
undefined
true
false
true
false
Map(2) { 'name' => 'GFG', 1 => 'One' }
Map(0) {}
0
2
Map(2) { 'a' => 1, 'b' => 2 }
Advantages of Using Maps: DSA Problems On Map

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4