JS: Literal Expression for Map

By Xah Lee. Date: . Last updated: .

There's no literal expression for map. but you can convert a literal expression of array or object into a map.

Array of pairs to map

const xx = new Map([[3, "n3"], [4, "n4"]]);

console.log(xx);
// Map { 3 => "n3", 4 => "n4" }

Note: the map constructor does not accept a object datatype.

Convert object to map

// convert a object to map
console.log(
 new Map(
  Object.entries({ dog: 2, cat: 9 }),
 ),
);
// Map(2) { "a" => 2, "b" => 9 }