Open In App

What is Map Coercion in JavaScript ?

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, Map coercion refers to the automatic conversion of an object or an iterable (such as an array) into a Map using the Map constructor. This coercion happens implicitly when an object or iterable with key-value pairs is provided as an argument to the Map constructor.

Example: Here, the array keyValuePairs contains nested arrays representing key-value pairs. When this array is passed as an argument to the Map constructor, it is coerced into a Map, and the resulting Map (myMap) contains the key-value pairs from the array.

Javascript




const keyValuePairs = [
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
];
 
// Map coercion using the Map constructor
const myMap = new Map(keyValuePairs);
 
console.log(myMap);


Output

Map(3) { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads