To create a map with initial key-value pairs in JavaScript, you can use the Map constructor along with an array of key-value pairs. This creates a new map object with predefined key-value pairs.
We can create a map in JavaScript with initial key-value pairs using the Map constructor and passing an array of key-value pairs.
For example,
myMap
. This variable will hold our map with initial key-value pairs.new Map()
constructor and pass an array of arrays, where each inner array contains a key-value pair. In JavaScript, the Map constructor can take an array of key-value pairs to initialize the map.myMap
variable. In this example, the map has string keys and integer values.let myMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Operations on the map
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
one: 1 two: 2 three: 3
We can create a map in JavaScript with initial key-value pairs of different types using the Map constructor.
For example,
studentGrades
. This variable will hold our map with initial key-value pairs where keys are strings (student names) and values are characters (grades).new Map()
constructor and pass an array of arrays, where each inner array contains a key-value pair. In JavaScript, the Map constructor can take an array of key-value pairs to initialize the map.studentGrades
variable. In this example, the map has string keys and string values representing grades.let studentGrades = new Map([
['Alice', 'A'],
['Bob', 'B'],
['Charlie', 'C']
]);
// Operations on the map
studentGrades.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
Alice: A Bob: B Charlie: C
We can create a map in JavaScript with initial key-value pairs where keys are integers and values are floats using the Map constructor.
For example,
productPrices
. This variable will hold our map with initial key-value pairs where keys are integers (product IDs) and values are floats (prices).new Map()
constructor and pass an array of arrays, where each inner array contains a key-value pair. In JavaScript, the Map constructor can take an array of key-value pairs to initialize the map.productPrices
variable. In this example, the map has integer keys and float values.let productPrices = new Map([
[101, 29.99],
[102, 39.99],
[103, 49.99]
]);
// Operations on the map
productPrices.forEach((value, key) => {
console.log(`Product ${key}: $${value}`);
});
Product 101: $29.99 Product 102: $39.99 Product 103: $49.99
In this tutorial, we learned How to create a Map with Initial Key-Value Pairs in JavaScript language with well detailed examples.