Loading lesson path
Concept visual
A JavaScript Map is an object that can store collections of key-value pairs, similar to a dictionary in other programming languages. Maps differ from standard objects in that keys can be of any data type.
Map keys can be any type (strings, numbers, objects, etc).
The Map remembers the original insertion order of the keys.
The number of items in a Map is easily retrieved using the size property.
Formula
Maps are optimized for frequent additions and removals of key - value pairs.Maps are iterable, allowing for direct use of for...of loops or methods like forEach().
The original order is preserved during iteration.
Formula
Maps are similar to both Objects (unique key/value collection) and Arrays (ordered values collection).But if you look close, Maps are most similar to Objects.
You create a JavaScript Map by: Create a new Map and add elements with Map.set() Passing an existing Array to the new Map() constructor
Create a new Map and add elements with Map.set()
// Create an empty Map const fruits = new Map();
// Set Map Values fruits.set("apples", 500);
fruits.set("bananas", 300);
fruits.set("oranges", 200);constructor:
// Create a Map const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);You can add elements to a Map with the set() method:
Example fruits.set("mangos", 100);method can also be used to change existing Map values:
Example fruits.set("apples", 200);method gets the value of a key in a Map:
Example fruits.get("apples"); // Returns 500// Returns object:
typeof fruits;instanceof
// Returns true:
fruits instanceof Map;Differences between JavaScript Objects and Maps: