JavaScript Maps
In JavaScript, a Map is a built-in data structure that allows for storing key-value pairs where both the keys and values can be of any data type
Map Methods
Method | Description |
---|---|
new Map() | Creates a new Map |
set() | Sets the value for a key in a Map |
get() | Gets the value for a key in a Map |
delete() | Removes a Map element specified by the key |
has() | Returns true if a key exists in a Map |
forEach() | Calls a function for each key/value pair in a Map |
entries() | Returns an iterator with the [key, value] pairs in a Map |
new Map()
You can create a Map by passing an Array to the new Map() constructor:
set()
You can add elements to a Map with the set() method:
Example
let myMap = new Map(); // Adding key-value pairs to the Map myMap.set('name', 'John'); myMap.set('age', 30); // Updating the value associated with an existing key myMap.set('age', 35); // Adding a new key-value pair myMap.set('country', 'USA'); console.log(myMap);
get()
The get() method gets the value of a key in a Map:
Example
let myMap = new Map(); myMap.set('name', 'John'); myMap.set('age', 30); myMap.set('country', 'USA'); console.log(myMap.get('name')); // Output: John console.log(myMap.get('age')); // Output: 30 console.log(myMap.get('city')); // Output: undefined (key 'city' does not exist)
delete()
The delete() method removes a Map element:
Example
let myMap = new Map(); myMap.set('name', 'John'); myMap.set('age', 30); myMap.set('country', 'USA'); console.log(myMap.delete('age')); // Output: true (the key 'age' was present and deleted) console.log(myMap.delete('city')); // Output: false (the key 'city' was not present) console.log(myMap); // Output: Map(2) { 'name' => 'John', 'country' => 'USA' }
has()
The has() method returns true if a key exists in a Map:
Example
let myMap = new Map(); myMap.set('name', 'John'); myMap.set('age', 30); myMap.set('country', 'USA'); console.log(myMap.has('name')); // Output: true (the key 'name' is present) console.log(myMap.has('city')); // Output: false (the key 'city' is not present)
foreach()
The forEach() method calls a function for each key/value pair in a Map:
Example
let myMap = new Map(); myMap.set('name', 'John'); myMap.set('age', 30); myMap.set('country', 'USA'); myMap.forEach((value, key) => { console.log(key + ': ' + value); });
entries()
The entries() method returns an iterator object with the [key, values] in a Map:
Example
let myMap = new Map(); myMap.set('name', 'John'); myMap.set('age', 30); myMap.set('country', 'USA'); let iterator = myMap.entries(); console.log(iterator.next().value); // Output: ['name', 'John'] console.log(iterator.next().value); // Output: ['age', 30] console.log(iterator.next().value); // Output: ['country', 'USA']You can click on above box to edit the code and run again.