A Map stores key-value pairs where the keys can be of any data type.
It also preserves the original insertion order of the keys.
You can create a JavaScript Map by either passing an array to new Map()
or by using Map.set()
to add key-value pairs.
A Map can be created by passing an array to the new Map()
constructor.
// Create a Map const fruits = new Map([ [“apples”, 500], [“bananas”, 300], [“oranges”, 200] ]); |
You can create a Map by providing an array to the new Map()
constructor.
// Create a Map const fruits = new Map(); // Set Map Values fruits.set(“apples”, 500); fruits.set(“bananas”, 300); fruits.set(“oranges”, 200); |
The set()
method can also be used to update existing values in a Map.
fruits.set(“apples”, 200); |
The get()
method retrieves the value associated with a key in a Map.
fruits.get(“apples”); // Returns 500 |