Matt
Matt

Reputation: 2821

Does JavaScript have a Map literal notation?

As of ES6, JavaScript has a proper Map object. I don't see a way to use a literal notation though, as you could with an Array or an Object. Am I missing it, or does it not exist?

Array: var arr = ["Foo", "Bar"];

Object: var obj = { foo: "Foo", bar: "Bar" };

Map: ???

Upvotes: 91

Views: 36144

Answers (4)

temeddix
temeddix

Reputation: 23

It's 2023 and map literal syntax is still not included in ECMAScript standard, though this NPM package called map-literal does exactly what you want.

Object.entries() can make a Map object for you, but it cannot deal with nested structures. Therefore you will need to use a package for that.

Upvotes: 1

Alex Shwarc
Alex Shwarc

Reputation: 885

There is a way to do it, like we do with literals

const fruits = new Map(Object.entries({apples: 1, bananas: 2}))

Upvotes: 23

Sterling Archer
Sterling Archer

Reputation: 22395

It's like a HashMap -- there is no literal version. You have to define it like you would a constructor.

You can read this topic which discusses map literals though, and why they should be added. It's basically others potential proposals on Map literals. I personally can't forsee a literal syntax in ES7, since Maps are very easy to use as is -- but in future proposals there could be syntactic sugar applied.

An example of potential literal notation was discussed using an octothorp (a hash) to look something like:

const myMap = Map#{expression("derp"): value("herp")};

Upvotes: 10

Bergi
Bergi

Reputation: 664484

No, ES6 does not have a literal notation for Maps or Sets.

You will have to use their constructors, passing an iterable (typically an array literal):

var map = new Map([["foo", "Foo"], ["bar", "Bar"], …]);

var set = new Set(["Foo", "Bar", …]);

There are some proposals to add new literal syntax to the language, but none made it into ES6 (and I'm personally not confident they will make it into any future version).

Upvotes: 95

Related Questions